diff --git a/public/assets/launch.js b/public/assets/launch.js
index e0468af..cd3e0f0 100644
--- a/public/assets/launch.js
+++ b/public/assets/launch.js
@@ -15,87 +15,71 @@
const pb = $('printBtn'); if (pb) pb.addEventListener('click', () => window.print());
const tok = me.username || me.refCode || me.memberId;
if (tok) document.querySelectorAll('[data-link]').forEach(el => { el.textContent = location.origin + '/join/' + tok; });
- // launch week swipes: four promoter emails, the member's link + FOUNDER code filled in (Marty, 2026-09-15)
- const LINK = location.origin + '/join/' + (tok || '') + '?promo=FOUNDER';
+ // launch swipes for LinkSpin's public launch, Sun 2026-11-15 9 AM Central (copy from campaign-2026-11/SWIPES.md, facts
+ // checked 2026-11-02). Replaced InstantAdPay's September founding-week set and its FOUNDER code (Marty 2026-11-05).
+ const BASE = location.origin + '/join/' + (tok || '');
+ const fill = t => t.replace(/\{link(?::(\w+))?\}/g, (m, v) => v ? BASE + '?v=' + v : BASE);
const SW = [
- { when: 'Day 1 · six days out', subject: 'Something opens Monday. I am bringing a few people in early.', body: `Quick one, because I want you positioned before this goes public.
+ { when: 'Short · any day before Sunday', subject: 'Opens to the world Sunday, 9 AM Central', body: `Quick one.
-I have been inside a new advertising platform for a week. It pays sponsors in the same transaction a package is bought, wallet to wallet, on the Polygon ledger where anyone can check it. No back office. No payday. I have watched the payouts land.
+LinkSpin opens to the world on Sunday, November 15 at 9 AM Central. I have been using it through pre-launch: one short link that rotates every page I promote, a bridge page built from any offer in a minute, and an ad slot on my site that pays me ad credits. All three are free with an email.
-It opens to everyone Monday, September 21 at 9 AM Central. Founding members are in now, and the people they bring in before then are the ones the launch traffic lands under.
+The paid side is advertising. A package buys ad credits, one cent each, and a public contract on Polygon splits each package to the sponsor line in the same transaction. Every payout is on the ledger.
-Joining is free with an email. This week the code FOUNDER gives you 500 ad credits to run a campaign on day one:
+Join before Sunday and you are placed under me; join after and you still get the same tools: {link}
-{link}
+Ad credits buy advertising, not income. Crypto carries risk of loss.`},
+ { when: 'Standard · the rotator story', subject: 'The rotator I wish I had ten years ago', body: `I have run link rotators for years and never trusted one. The clicks never matched my tracker, dead links kept serving, and there was no report worth reading.
-No income is promised. It is an ad platform with a referral program. But the payment mechanics are real and public, and that is why I am in.
+LinkSpin is the first one I keep open all day.
-Look before Monday. I will walk you through the first three steps.`},
- { when: 'Day 2 · five days out', subject: 'Five hundred free credits, and what you can do with them', body: `Yesterday I sent you a link. Here is what is on the other side of it.
+One short link stands in for every page I promote. I set the share each page gets, give a page hours of the day, pause it when it stops pulling, and name a fallback. Every destination is health-checked every 30 minutes and paused for me if it dies. My tracker's click id rides through. The report shows which page converts, by source, country and device, with bots dropped on the server.
-You join free with your email. Every day you view a short set of ads and earn credits. Credits run your own ads: banners, text ads, video ads, solo mailings, verified visits, across the whole network.
+It also builds a bridge, review or squeeze page from any offer I paste in, published on a clean domain with the leads going to my list. And one script tag turns the empty ad space on my site into a zone that pays me ad credits.
-This week the FOUNDER code adds 500 credits on top the moment you join, enough to launch a real campaign pointed at whatever you are promoting. Watch it deliver before Monday, when everyone else arrives.
+All of that is free with an email. The paid side is advertising: six packages, $10 to $500, one credit per cent of delivery, and a verified contract on Polygon that splits each package to the sponsor line in the same transaction it sells in.
-The other half is simple. When someone you invite buys an ad package, the contract pays you 50 percent instantly. Level two gets 20 percent, level three 10 percent. Same transaction, on the public ledger.
+LinkSpin opens to the world Sunday, November 15 at 9 AM Central. Have a look before then: {link:links}
-{link}
-
-Use the code before it expires Monday morning. Then tell me you are in and I will show you the checklist.`},
- { when: 'Day 4 · the weekend', subject: 'The two people you bring in this weekend', body: `The doors open Monday morning and I am spending the weekend getting my first people set up. I want you to be one of them.
-
-Here is why the weekend matters. Everyone who joins now is a founding member. The traffic that arrives Monday lands under whoever is already in and set up. Two people under you before Monday, and your line is built when the wave hits.
-
-Setup takes ten minutes: username, link a wallet, switch on payouts. Then share your link. The site gives you posts, swipes, banners and a leaderboard with weekly credit prizes for the top sponsors.
-
-Join with the FOUNDER code and the 500 credits are yours:
-
-{link}
-
-Message me when you are in and I will go through the checklist with you before Monday.`},
- { when: 'Day 6 · Sunday evening', subject: 'Doors open tomorrow at 9 AM Central', body: `Last note before the launch.
-
-LinkSpin opens to the public tomorrow, Monday, at 9 AM Central. After that the FOUNDER code is gone. Tonight it still gives you 500 free ad credits.
-
-If you join tonight you are in as a founding member with a campaign already funded and your link ready when the first wave arrives. If you wait, you join the wave.
-
-Free to join, real advertising, and every payment lands in your own wallet the second it happens, on a ledger anyone can read. No income promises. Just mechanics you can verify.
-
-{link}
-
-I will be online from 8 AM tomorrow walking people through the first three steps. Get in tonight and you are ahead of them.`}
+Ad credits buy advertising, not income. Payouts come only from purchases in your line. Crypto carries risk of loss.`}
];
- // short posts and a DM for the same days, one per day, link + code included
const POSTS = [
- { when: 'Day 1 · six days out', text: `Something I have been inside for a week opens to the public Monday, September 21 at 9 AM Central. An ad platform that pays sponsors in the same transaction a package is bought, on the Polygon ledger where anyone can check it. Free to join. Code FOUNDER gives you 500 ad credits before then. No income promises, just mechanics you can verify. {link}` },
- { when: 'Day 2 · five days out', text: `500 free ad credits for joining before Monday. View a short daily set of ads, earn more, run banners, text ads, video ads and solo mailings across the network. When someone you invite buys a package, the contract pays you 50 percent instantly, wallet to wallet. Code FOUNDER. {link}` },
- { when: 'Day 4 · the weekend', text: `The doors open Monday morning. Everyone joining this weekend is a founding member, and the launch traffic lands under whoever is already set up. Ten minutes to set up, 500 credits with code FOUNDER, and a leaderboard that pays weekly credit prizes to the top sponsors. {link}` },
- { when: 'Day 6 · Sunday evening', text: `Doors open tomorrow, 9 AM Central. Tonight the FOUNDER code still gives you 500 free ad credits; tomorrow it is gone. Free to join, real advertising, every payment on a public ledger. Get in tonight and you are ahead of the wave. {link}` },
- { when: 'Text or DM · any day', text: `Hey, I am in something that opens publicly Monday and I am bringing a few people in early. Free to join, real advertising, every payment lands in your own wallet the second it happens. Use code FOUNDER for 500 free credits. Ten minutes to set up and I will walk you through it: {link}` }
+ { when: 'X · one link', text: `One short link that rotates every page I promote, with weights, hours and a fallback, and a report that shows which page converts. LinkSpin is open for pre-launch and goes live to the world Nov 15. Free, try a spin with no account: {link:links}` },
+ { when: 'Facebook · three tools', text: `Three tools I used to pay for separately, now free with an email address.
+
+One link that rotates every page I promote and reports which one converts. A page builder that turns any offer I paste in into a bridge, review or squeeze page on a clean domain, with the leads going to my own list. And an ad slot for my own site that pays me ad credits for every viewable view.
+
+It is open for pre-launch now and goes live to the world on Sunday, November 15. The paid side is advertising, split by a public contract on Polygon in the same transaction; read that part on the site before you spend a dollar.
+
+{link:stack}
+
+Ad credits buy advertising, not income. Crypto carries risk of loss.` },
+ { when: 'Telegram or WhatsApp group', text: `Quick one for the group. LinkSpin opens to the world Sunday, Nov 15, 9 AM Central. Free with an email: one link that rotates every page you promote, a bridge-page builder, and an ad slot for your site that pays ad credits. Members who join before Sunday are placed under whoever brought them. Tour: {link}` },
+ { when: 'Text a friend', text: `Found a link rotator that is actually free and actually reports. One link spins every page you promote. It opens to everyone Sunday 9 AM Central; join before and you are on my team: {link:links}` }
];
const pl = $('postList');
if (pl) {
- pl.innerHTML = POSTS.map((s, i) => '
').join('');
- }
- // ── overview v3 charts: hand-rolled SVG/CSS, real data only ──
- const esc = s => String(s == null ? '' : s).replace(/[&<>"]/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"' }[c]));
+// My account: email-first join/login, wallet link at purchase time,
+// free payout activation, invite link, on-chain activity.
+(async function () {
+ // back-office shell: no marketing nav here; rehearsal notice lives in the top bar
+ const $ = IAP.$;
+ try {
+ const c = await IAP.getConfig();
+ if (c.rehearsal && $('boRehearsal')) {
+ $('boRehearsal').hidden = false;
+ $('boRehearsal').innerHTML = 'Testnet rehearsal · ' + c.chainName;
+ }
+ if (c.rehearsal && $('faucetCard')) $('faucetCard').hidden = false;
+ } catch (e) {}
+ // if they arrived through a sponsor's link, show who they're joining under
+ (async () => {
+ try {
+ const sp = await (await fetch('/api/sponsor')).json();
+ if (sp && sp.invited && sp.name && $('sponsorNote')) { $('sponsorNoteName').textContent = sp.name; $('sponsorNote').hidden = false; }
+ } catch (e) {}
+ })();
+
+ async function api(path, body) {
+ const r = await (await fetch(path, { method: 'POST',
+ headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body || {}) })).json();
+ if (r.error) throw new Error(r.error);
+ return r;
+ }
+
+ // holding tank (2026-10-27): no sponsor yet, so the free Switch on payouts waits for an adopter (24 hours at most).
+ // A purchase is never held: buying goes ahead as before.
+ const holdLeft = ms => { const m = Math.max(1, Math.round(ms / 60000)); const h = Math.floor(m / 60); return h ? h + ' h ' + (m % 60) + ' min' : m + ' min'; };
+ function tankHoldText(h) {
+ let t = "You're being matched with a sponsor. Payouts switch on as soon as someone picks you up (within 24 hours).";
+ if (h && h.until) { const ms = h.until - Date.now(); t += ms > 0 ? ' Time left: ' + holdLeft(ms) + '.' : ' Any minute now.'; }
+ return t;
+ }
+ let TANK_HOLD = null;
+ function nextMove(d) {
+ if (TANK_HOLD && d.address && !d.memberId) return tankHoldText(TANK_HOLD);
+ if (!d.address) return 'Grab your link below and start sharing today. Then link your wallet (one free signature) so every payment can lock to you before your people start buying.';
+ if (!d.memberId) return 'Your wallet is linked. Switch on payouts above (one free transaction) and every purchase in your line pays you the moment it happens.';
+ if (d.buyerCount === 0) return 'Payouts are on and your link is live. Your next milestone: your first buyer of $25 or more. Every direct pays you 50 percent from their very first package.';
+ if (d.buyerCount === 1) return 'One qualifying buyer down, one to go. Your next $25+ buyer unlocks level 2: 20 percent of everything your people’s people buy.';
+ if (d.buyerCount < 5) return 'Level 2 is open. ' + (5 - d.buyerCount) + ' more qualifying buyer(s) unlock level 3 and the full three-level flow.';
+ return 'Fully qualified. Every level pays you, and you catch the pass-ups that under-qualified positions below you let slip. Keep sharing and keep your campaigns running.';
+ }
+ // featured rotation strip on the overview
+ let featItems = [], featIdx = 0, featTimer = null;
+ function renderOneFeatured() {
+ if (!featItems.length) return;
+ const i = featItems[featIdx % featItems.length];
+ $('featStrip').innerHTML = '' + esc(i.title) + ''
+ + (i.by ? '' + esc(i.by) + '' : '') + '';
+ }
+ async function loadFeatured() {
+ try {
+ const r = await (await fetch('/api/featured')).json();
+ const card = $('featuredCard'); if (!card) return;
+ if (!r.items || !r.items.length) { card.hidden = true; return; }
+ card.hidden = false;
+ featItems = r.items; featIdx = Math.floor(Math.random() * featItems.length);
+ $('featSub').textContent = r.items.length + ' link' + (r.items.length === 1 ? '' : 's') + ' in rotation';
+ renderOneFeatured(); // show ONE at a time (true rotation), cycle if more than one
+ clearInterval(featTimer);
+ if (featItems.length > 1) featTimer = setInterval(() => { featIdx++; renderOneFeatured(); }, 6000);
+ // self-sell: today's open slots + a CTA to feature your own link
+ try {
+ const st = await (await fetch('/api/featured/stats')).json();
+ const today = (st.occupancy || []).find(d => d.offset === 0);
+ const cta = $('featCta');
+ if (cta) {
+ cta.innerHTML = (today ? '' + today.open + ' of ' + today.cap + ' featured slots open today. ' : '')
+ + 'Feature your link →';
+ const fb = $('featBuy');
+ if (fb) fb.addEventListener('click', e => { e.preventDefault(); setPane('campaigns'); const ct = $('cType'); if (ct) { ct.value = 'featured'; ct.dispatchEvent(new Event('change')); } });
+ }
+ } catch (e) {}
+ } catch (e) {}
+ }
+
+ // achievement badges: the milestone ladder as unlockable medals + share-to-image
+ const BADGES = [ // ribbonY = vertical center of the member's name: the clear band between the art's body line and the footer bar (all four share it)
+ { key: 'payouts', label: 'Spark', sub: 'payouts on', img: '/badges/badge-spark.jpg', ribbonY: 0.873 },
+ { key: 'firstBuyer', label: 'Surge', sub: 'first qualifying buyer', img: '/badges/badge-surge.jpg?v=2', ribbonY: 0.873 },
+ { key: 'level2', label: 'Circuit', sub: '2 qualifying buyers', img: '/badges/badge-circuit.jpg?v=2', ribbonY: 0.873 },
+ { key: 'level3', label: 'Nexus', sub: 'fully qualified', img: '/badges/badge-nexus.jpg?v=2', ribbonY: 0.873 }
+ ];
+ let lastMilestones = [];
+ function renderBadges(d) {
+ const reached = d.milestonesReached || [];
+ lastMilestones = reached;
+ const strip = $('badgeStrip');
+ if (!strip) return;
+ $('badgeCard').hidden = false;
+ strip.innerHTML = BADGES.map(b => {
+ const got = reached.includes(b.key);
+ return '
'
+ + ''
+ + '
' + b.label + '
' + b.sub + '
'
+ + (got ? ' ' : '
🔒 locked
') + '
';
+ }).join('');
+ strip.querySelectorAll('[data-badge]').forEach(btn =>
+ btn.addEventListener('click', () => shareBadge(btn.dataset.badge, d)));
+ strip.querySelectorAll('[data-badgepost]').forEach(btn =>
+ btn.addEventListener('click', () => postBadge(btn.dataset.badgepost, d, btn, true)));
+ fetch('/api/my/badge-posted').then(r => r.json()).then(r => { // the manual button is the admin's only (Marty, 2026-09-13)
+ if (r.canPost) strip.querySelectorAll('[data-badgepost]').forEach(b => { b.hidden = false; });
+ (r.posted || []).forEach(k => { const b = strip.querySelector('[data-badgepost="' + k + '"]'); if (b) { b.textContent = 'Posted ✓'; b.disabled = true; } });
+ }).catch(() => {});
+ // celebrate anything newly granted this load, and post the branded badge to the team channels (Marty, 2026-09-13)
+ if (d.milestonesGranted && d.milestonesGranted.length) {
+ const total = d.milestonesGranted.reduce((s, g) => s + g.credited, 0);
+ const names = d.milestonesGranted.map(g => (BADGES.find(b => b.key === g.key) || {}).label).filter(Boolean).join(', ');
+ IAP.status('🏆 Achievement unlocked: ' + names + ' — +' + total + ' bonus credits!', 'ok');
+ d.milestonesGranted.forEach((g, i) => setTimeout(() => postBadge(g.key, d, strip.querySelector('[data-badgepost="' + g.key + '"]')), 800 + i * 1500));
+ }
+ }
+ // draw the badge with the member's name on the ribbon; cb(canvas) or cb(null)
+ function composeBadge(key, d, cb) {
+ const b = BADGES.find(x => x.key === key); if (!b) return cb(null);
+ const who = d.username ? d.username : d.memberId ? 'member #' + d.memberId : '';
+ const img = new Image();
+ img.onload = () => {
+ const c = document.createElement('canvas'); c.width = img.width; c.height = img.height;
+ const x = c.getContext('2d');
+ x.drawImage(img, 0, 0);
+ if (who) {
+ x.textAlign = 'center'; x.textBaseline = 'middle';
+ let fs = Math.round(c.width * 0.052); // the name sits in the clear band under the art's own text (Marty 2026-10-18: it overlapped ACHIEVEMENT UNLOCKED)
+ x.font = 'bold ' + fs + 'px Sora, "Segoe UI", sans-serif';
+ while (fs > 20 && x.measureText(who).width > c.width * 0.8) { fs -= 2; x.font = 'bold ' + fs + 'px Sora, "Segoe UI", sans-serif'; }
+ const y = c.height * (b.ribbonY || 0.75);
+ x.lineJoin = 'round'; x.lineWidth = Math.max(3, Math.round(c.width * 0.008));
+ x.strokeStyle = 'rgba(4,20,15,.9)'; x.strokeText(who, c.width / 2, y);
+ x.fillStyle = '#ffd15c'; x.fillText(who, c.width / 2, y);
+ }
+ cb(c);
+ };
+ img.onerror = () => cb(null);
+ img.src = b.img;
+ }
+ async function postBadge(key, d, btn, manual) {
+ if (btn && btn.disabled) return;
+ if (btn) { btn.disabled = true; btn.textContent = 'Posting…'; }
+ composeBadge(key, d, c => {
+ if (!c) { if (btn) { btn.disabled = false; btn.textContent = 'Post to Telegram'; } return; }
+ c.toBlob(async bl => {
+ try {
+ const r = await (await fetch('/api/my/badge-post?key=' + encodeURIComponent(key) + (manual ? '&manual=1' : ''), { method: 'POST', headers: { 'Content-Type': 'image/jpeg' }, body: bl })).json();
+ if (r.error) throw new Error(r.error);
+ if (btn) { btn.textContent = 'Posted ✓'; btn.disabled = true; }
+ if (!r.already) IAP.status('Your badge is posted in the team channels.', 'ok');
+ } catch (e) { if (btn) { btn.disabled = false; btn.textContent = 'Post to Telegram'; } IAP.status(e.message || 'Could not post the badge.', 'bad'); }
+ }, 'image/jpeg', 0.86);
+ });
+ }
+ // Share: a picker (Marty, 2026-09-13). The composed badge is stored once so a public page at
+ // /b// carries it as the preview image; every network gets that link.
+ function shareBadge(key, d) {
+ const b = BADGES.find(x => x.key === key); if (!b) return;
+ if (!d.username) { IAP.status('Pick a username first; your share page carries it.', 'bad'); return; }
+ IAP.status('Preparing your ' + b.label + ' badge…', 'ok');
+ composeBadge(key, d, c => {
+ if (!c) { IAP.status('Could not load the badge art.', 'bad'); return; }
+ c.toBlob(async bl => {
+ let page = null;
+ try { const r = await (await fetch('/api/my/badge-image?key=' + encodeURIComponent(key), { method: 'POST', headers: { 'Content-Type': 'image/jpeg' }, body: bl })).json(); if (r.error) throw new Error(r.error); page = r.page; }
+ catch (e) { IAP.status(e.message || 'Could not prepare the share page.', 'bad'); return; }
+ openShareSheet(b, d, bl, page);
+ }, 'image/jpeg', 0.9);
+ });
+ }
+ function openShareSheet(b, d, blob, page) {
+ const text = 'I just unlocked the ' + b.label + ' badge on LinkSpin (' + b.sub + '). Advertising that pays you back, on-chain, the same second a package sells.';
+ const enc = encodeURIComponent;
+ const links = [
+ ['X', 'https://x.com/intent/tweet?text=' + enc(text) + '&url=' + enc(page)],
+ ['Facebook', 'https://www.facebook.com/sharer/sharer.php?u=' + enc(page)],
+ ['Telegram', 'https://t.me/share/url?url=' + enc(page) + '&text=' + enc(text)],
+ ['WhatsApp', 'https://wa.me/?text=' + enc(text + ' ' + page)],
+ ['LinkedIn', 'https://www.linkedin.com/sharing/share-offsite/?url=' + enc(page)]
+ ];
+ const back = document.createElement('div'); back.className = 'modal-back'; back.style.zIndex = '200';
+ back.innerHTML = '
'
+ + '
Share your ' + b.label + ' badge
Each option shares your badge page, which shows the image and your join link.
').join('');
+ }
+ // ── overview v3 charts: hand-rolled SVG/CSS, real data only ──
+ const esc = s => String(s == null ? '' : s).replace(/[&<>"]/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"' }[c]));
// chart colours come from the live theme tokens (2026-11-01): read at draw time so a theme switch repaints correctly
- const CH = new Proxy({}, { get: (_, k) => { const cs = getComputedStyle(document.documentElement); const v = { mint: '--mint', cyan: '--cyan', violet: '--violet', amber: '--amber', track: '--muted-soft' }[k]; return (v && cs.getPropertyValue(v).trim()) || { mint: '#3b9dff', cyan: '#54ccff', violet: '#9d7dff', amber: '#ffb238', track: 'rgba(139,166,156,.18)' }[k]; } });
- function bars(el, xel, data) { // data: [{v,label,tip,alt}]
- if (!el) return;
- const max = Math.max(1, ...data.map(d => d.v));
- el.innerHTML = data.length
- ? data.map(d => '').join('')
- : ''.repeat(8);
- if (xel) xel.innerHTML = data.map(d => '' + esc(d.label) + '').join('');
- }
- function donut(el, segs, center) { // segs sum to the ring; r=15.9155 → circumference 100
- if (!el) return;
- const total = segs.reduce((s, x) => s + x.v, 0);
- let off = 25, out = '';
- if (total > 0) for (const s of segs) {
- const len = s.v / total * 100;
- if (len <= 0 || s.color === 'none') { off -= Math.max(0, len); continue; }
- out += '';
- off -= len;
- }
- out += '' + esc(center.big) + ''
- + '' + esc(center.small) + '';
- el.innerHTML = out;
- }
- function legend(el, rows) {
- if (el) el.innerHTML = rows.map(r => '
'
- + esc(r.label) + ' ' + esc(r.v) + '
').join('');
- }
- async function loadCharts(d) {
- // credit composition donut + today's viewing ring (live balances)
- try {
- const st = await (await fetch('/api/my/earn')).json();
- if (!st.error) {
- // one rule: a balance is what is NOT committed to a live campaign. Budgets are
- // set aside when a campaign starts and spend down inside Campaigns, so these
- // numbers only move when a campaign is created, topped up or paused
- const purchased = d.credits || 0, earned = d.earnedCredits != null ? d.earnedCredits : (st.earnedAvailable != null ? st.earnedAvailable : (st.earned || 0)), inC = d.inCampaigns || 0;
- $('dbCredits').textContent = (purchased + earned).toLocaleString();
- // the Wallet tab card showed on-chain credits only, so promo/earned credits looked like 0 there (Jim, 2026-09-13)
- if ($('creditLine')) $('creditLine').innerHTML = (purchased + earned).toLocaleString() + ' ' + purchased.toLocaleString() + ' purchased · ' + earned.toLocaleString() + ' earned';
- $('dbCreditsSub').textContent = purchased.toLocaleString() + ' purchased' + (d.creditedCredits ? ' (' + d.creditedCredits.toLocaleString() + ' credited to you)' : '') + ' · ' + earned.toLocaleString() + ' earned' + (inC ? ' · ' + inC.toLocaleString() + ' in campaigns' : '');
- donut($('chDonut'),
- [{ v: purchased, color: CH.mint }, { v: earned, color: CH.cyan }, { v: inC, color: CH.amber }],
- { big: (purchased + earned).toLocaleString(), small: 'available' });
- legend($('chDonutLegend'), [
- { color: CH.mint, label: 'Purchased, available', v: purchased.toLocaleString() },
- { color: CH.cyan, label: 'Earned, available', v: earned.toLocaleString() },
- { color: CH.amber, label: 'In live campaigns', v: inC.toLocaleString() }]);
- const done = Math.min(st.views || 0, st.target || 5), left = Math.max(0, (st.target || 5) - done);
- donut($('chRing'), [{ v: done, color: st.claimed ? CH.mint : CH.cyan }, { v: left, color: 'none' }],
- { big: done + '/' + (st.target || 5), small: st.claimed ? 'claimed' : 'ads viewed' });
- legend($('chRingLegend'), [
- { color: st.claimed ? CH.mint : CH.cyan, label: 'Viewed today', v: done },
- { color: CH.track, label: 'To go', v: left },
- { color: CH.amber, label: 'Claim pays', v: '+' + (st.claimCredits || 0) + ' credits' }]);
- }
- } catch (e) {}
- // recent on-chain payouts, sized to scale, oldest→newest
- try {
- let evs = [];
- if (d.memberId) {
- const a = await (await fetch('/api/my/activity')).json();
- evs = (a.earnings || []).filter(e => e.amountWei).sort((x, y) => x.block - y.block).slice(-12);
- }
- bars($('chEarnBars'), $('chEarnX'), evs.map(e => ({
- v: Number(BigInt(e.amountWei) / 1000000000000n) / 1e6,
- label: e.type === 'AwardPaid' ? 'award' : 'L' + (e.tier || 1),
- tip: IAP.fmtPol(e.amountWei) + ' POL', alt: e.type === 'AwardPaid' })));
- if (!evs.length) $('chEarnSub').textContent = d.memberId
- ? 'no payouts yet — share your link' : 'activate a package to start earning';
- } catch (e) {}
- // campaign delivery: impressions per campaign
- try {
- const r = await (await fetch('/api/my/campaigns')).json();
- const cs = (r.campaigns || []).slice(0, 8);
- bars($('chCampBars'), $('chCampX'), cs.map(c => ({
- v: c.imps || 0, label: String(c.name || c.type).slice(0, 9),
- tip: (c.name || c.type) + ': ' + (c.imps || 0) + ' imps · ' + (c.clicks || 0) + ' clicks',
- alt: c.type === 'text' })));
- if (!cs.length) $('chCampSub').textContent = 'no campaigns yet — place your first ad';
- } catch (e) {}
- }
- // ── live updates: subscribe to the chain event stream so the members area
- // reacts to on-chain changes (payouts, qualifications) without a refresh ──
- let MYID = 0;
- // synthesized sounds (no asset files; CSP-safe). cha-ching on a payment, pop on a message.
- function playSound(kind) {
- try {
- const AC = window.AudioContext || window.webkitAudioContext; if (!AC) return;
- const ctx = window.__iapAC || (window.__iapAC = new AC());
- if (ctx.state === 'suspended') ctx.resume();
- const now = ctx.currentTime;
- const tone = (freq, at, dur, type, peak) => {
- const o = ctx.createOscillator(), g = ctx.createGain();
- o.type = type || 'sine'; o.frequency.value = freq;
- g.gain.setValueAtTime(0.0001, now + at);
- g.gain.exponentialRampToValueAtTime(peak || 0.22, now + at + 0.02);
- g.gain.exponentialRampToValueAtTime(0.0001, now + at + dur);
- o.connect(g).connect(ctx.destination); o.start(now + at); o.stop(now + at + dur + 0.02);
- };
- if (kind === 'chaching') { tone(1318, 0, 0.34, 'sine', 0.25); tone(1760, 0.09, 0.4, 'sine', 0.25); }
- else { tone(680, 0, 0.16, 'triangle', 0.18); tone(1020, 0.05, 0.16, 'triangle', 0.16); }
- } catch (e) {}
- }
- function startLiveFeed() {
- if (window.__iapFeed || !window.EventSource) return;
- try {
- const es = new EventSource('/api/feed/live');
- window.__iapFeed = es;
- es.onmessage = m => { let ev; try { ev = JSON.parse(m.data); } catch (e) { return; } handleLiveEvent(ev); };
- // browser auto-reconnects on error; nothing to do
- } catch (e) {}
- }
- let liveRefreshT = null;
- function liveRefresh() { // debounce a burst of events into one refresh
- clearTimeout(liveRefreshT);
- liveRefreshT = setTimeout(() => { loadDashboard(); try { loadLineage(); } catch (e) {} }, 600);
- }
- // community toasts (Marty, 2026-09-12: keep the dashboard feeling alive): everyone else's joins,
- // purchases, payouts, qualifications, tank arrivals and adoptions, in a second, quieter toast so
- // they never replace a personal one. At most one every 4 s; a burst shows the latest.
- let liveT = 0, liveQ = null;
- function communityToast(msg) {
- const now = Date.now();
- if (now - liveT < 4000) { liveQ = msg; if (!communityToast._q) communityToast._q = setTimeout(() => { communityToast._q = null; const m = liveQ; liveQ = null; if (m) communityToast(m); }, 4200 - (now - liveT)); return; }
- liveT = now;
- let el = document.getElementById('liveToast');
- if (!el) { el = document.createElement('div'); el.id = 'liveToast'; el.setAttribute('role', 'status'); el.style.cssText = 'position:fixed;left:16px;bottom:16px;z-index:90;max-width:min(360px,calc(100vw - 32px));background:var(--panel-solid);border:1px solid var(--line-strong);border-left:3px solid var(--mint);border-radius:12px;padding:10px 14px;font-size:14px;box-shadow:0 10px 30px rgba(0,0,0,.4);transition:opacity .3s'; document.body.appendChild(el); }
- el.textContent = msg; el.hidden = false; el.style.opacity = '1';
- clearTimeout(communityToast._t); communityToast._t = setTimeout(() => { el.style.opacity = '0'; setTimeout(() => { el.hidden = true; }, 350); }, 6000);
- }
- function handleLiveEvent(ev) {
- if (!ev || !ev.type) return;
- const nm = id => (ev.names && ev.names[id]) ? '@' + ev.names[id] : 'member #' + id;
- // site-wide activity (not about me): joins, tank, adoptions, purchases, payouts, qualifications
- if (ev.type === 'Joined') { communityToast('👋 ' + ev.name + ' just joined' + (ev.tank ? ' and is waiting for a sponsor in the holding tank' : '')); liveRefresh(); return; }
- if (ev.type === 'Adopted') { communityToast('🤝 ' + ev.sponsor + ' picked up ' + ev.member + ' from the holding tank'); liveRefresh(); return; }
- if (ev.type === 'Contest') { communityToast('🏆 ' + ev.winner + ' won the ' + (ev.kind === 'week' ? 'weekly' : 'monthly') + ' referral contest'); return; }
- if (ev.type === 'Badge') { communityToast('🏆 ' + ev.member + ' unlocked ' + ev.label); return; }
- if (ev.type === 'Released') { communityToast('🪣 ' + ev.sponsor + ' returned ' + ev.member + ' to the holding tank'); liveRefresh(); return; }
- const mine = MYID && (ev.recipientId === MYID || ev.toId === MYID || ev.sponsorId === MYID || ev.skippedId === MYID || ev.buyerId === MYID);
- if (!mine) {
- if (ev.type === 'Purchase' && ev.buyerId) communityToast('🧾 ' + nm(ev.buyerId) + ' just bought a $' + Math.round((ev.priceCents || 0) / 100) + ' package');
- else if (ev.type === 'TierPaid' && ev.recipientId) communityToast('💸 ' + nm(ev.recipientId) + ' just got paid ' + IAP.fmtPol(ev.amountWei) + ' POL');
- else if (ev.type === 'BuyerCounted' && ev.sponsorId) communityToast('🎯 ' + nm(ev.sponsorId) + ' now has ' + ev.newCount + ' qualifying buyer' + (ev.newCount === 1 ? '' : 's'));
- else if (ev.type === 'MemberActivated' && ev.id) communityToast('⚡ ' + nm(ev.id) + ' switched on payouts');
- return;
- }
- if (!MYID) return;
- let toast = null, kind = 'ok';
- let sound = null;
- if (ev.type === 'TierPaid' && ev.recipientId === MYID) { toast = '💸 You earned a level-' + ev.tier + ' payout of ' + IAP.fmtPol(ev.amountWei) + ' POL!'; sound = 'chaching'; }
- else if (ev.type === 'AwardPaid' && ev.toId === MYID) { toast = '💸 You received ' + IAP.fmtPol(ev.amountWei) + ' POL!'; sound = 'chaching'; }
- else if (ev.type === 'BuyerCounted' && ev.sponsorId === MYID) toast = '🎯 A referral just qualified — you now have ' + ev.newCount + ' qualifying buyer' + (ev.newCount === 1 ? '' : 's') + '!';
- else if (ev.type === 'PassedUp' && ev.skippedId === MYID) { toast = '⚠️ A level-' + ev.tier + ' payout passed you by. Get qualified to catch these.'; kind = 'bad'; }
- else if (ev.type === 'Purchase' && ev.buyerId === MYID) toast = '✅ Purchase settled on-chain — your credits are updated.';
- else if (ev.type === 'MemberActivated' && ev.sponsorId === MYID) toast = '🤝 A new member just activated in your line!';
- if (toast) { IAP.status(toast, kind); if (sound) playSound(sound); liveRefresh(); }
- }
-
- // training center: videos + materials (admin-curated via data/training.json)
- async function loadTraining() {
- try {
- const r = await (await fetch('/api/training')).json();
- const el = $('trainingList'); if (!el) return;
- const items = r.items || [];
- if (!items.length) { el.innerHTML = '
Training materials are being added. Check back soon.
'; return; }
- // section pills at the top: one per group, plus All; the active pill filters the list
- const groups = [...new Set(items.map(it => it.group).filter(Boolean))];
- const pills = $('trainingPills');
- const want = loadTraining.filter || 'all';
- if (pills) {
- pills.hidden = groups.length < 2;
- pills.innerHTML = ['all', ...groups].map(g => '').join('');
- pills.querySelectorAll('[data-tg]').forEach(b => b.addEventListener('click', () => { loadTraining.filter = b.dataset.tg; loadTraining(); }));
- }
- const shown = want === 'all' ? items : items.filter(it => it.group === want);
- let lastGroup = null;
- el.innerHTML = shown.map(it => {
- // optional section header: entries carry a `group`; a header renders when it changes
- let head = '';
- if (it.group && it.group !== lastGroup) { lastGroup = it.group; head = '
' + esc(it.group) + '
'; }
- const isVid = it.videoUrl && /\.(mp4|webm)(\?|$)/i.test(it.videoUrl);
- // poster: the admin list can carry one; otherwise assume a .jpg next to the .mp4 (the pipeline uploads both)
- const poster = it.posterUrl || (isVid ? it.videoUrl.replace(/\.(mp4|webm)(\?.*)?$/i, '.jpg$2') : '');
- const media = isVid ? '' : '';
- const links = [];
- if (it.videoUrl && !isVid) links.push('Watch');
- if (it.docUrl) links.push('Open material');
- return head + '
' + esc(it.title || 'Lesson') + '
'
- + (it.desc ? '
' + esc(it.desc) + '
' : '') // pre-line: a written lesson keeps its paragraphs (Banner Spin, 2026-10-20)
- + (media ? '
' + media + '
' : '')
- + (links.length ? '
' + links.join(' ') + '
' : '') + '
';
- }).join('');
- } catch (e) {}
- }
- // visual line tree on the Overview: YOU + three levels, qualified directs in gold
- async function loadLineTree(buyerCount) {
- try {
- const r = await (await fetch('/api/my/line')).json();
- const el = $('lineTree'); if (!el) return;
- const levels = r.levels || [];
- const total = levels.reduce((n, L) => n + L.members.length, 0);
- if ($('treeSub')) $('treeSub').textContent = total ? total + ' across 3 levels' : 'share your link to grow';
- const chip = (m, q) => '' + esc(String(m.name || 'M').replace(/^@/, '').slice(0, m.own ? 20 : 14)) + (m.buyers ? '' + m.buyers + '' : '') + '';
- const rowFor = lvl => {
- const L = levels.find(x => x.level === lvl); const members = L ? L.members : [];
- // gold = the contract counted this member as one of your qualifying buyers (not "the first N chips")
- let html = members.map(m => chip(m, !!(m.qualified || m.bought))).join(''); // gold on every level = made their $25+ buy
- if (lvl <= 2 && members.length < (lvl === 1 ? 2 : 4)) html += '+ open';
- if (!html) html = '+ open';
- return '
L' + lvl + '
' + html + '
';
- };
- el.innerHTML = '
YOU
' + rowFor(1) + rowFor(2) + rowFor(3);
- } catch (e) {}
- }
- // "What's new" card: latest notes + what is being built; a dot marks notes newer than the member's last look (Marty, 2026-09-14)
- let newsLoaded = false;
- async function loadNews() {
- if (newsLoaded || !$('newsCard')) return; newsLoaded = true;
- try {
- const r = await (await fetch('/api/releases')).json();
- if (!r.notes.length && !r.roadmap.length) return;
- let seen = ''; try { seen = localStorage.getItem('iap.news.seen') || ''; } catch (e) {}
- const esc = t => String(t == null ? '' : t).replace(/[&<>"]/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"' }[c]));
- const notes = r.notes.slice(0, 3).map(n => '
').join('');
- const copy = {
- user: ['Pick your username', 'It becomes your invite link and your public page, and it is permanent.', 'Choose a username', () => showOnboard(true)],
- wallet: ['Link your wallet', 'Your payouts land in a wallet you control, so the site needs to know which one is yours. One free signature, no purchase. MetaMask recommended; Phantom users switch Polygon on first. Never held crypto? The wallet guide walks you through it.', 'Link my wallet', () => jumpTo('wallet', 'linkBtn')],
- payouts: ['Switch on payouts', 'One small transaction registers your wallet with the contract so commissions can reach it. Buying any package does this automatically.', 'Activate payouts', () => jumpTo('wallet', 'activateBtn')],
- package: ['Your first package', 'From $10. The $25 package is the one that counts you as a qualifying buyer for your sponsor and unlocks adopting from the holding tank.', 'See packages', () => jumpTo('buy', null)]
- }[cur.k];
- if (cur.k === 'payouts' && TANK_HOLD) { copy[0] = 'Matching you with a sponsor'; copy[1] = tankHoldText(TANK_HOLD); copy[2] = null; } // no activate button while held
- $('gsNow').innerHTML = '
').join('');
- wrap.appendChild(t);
- }
- // overview recent-activity widget: chain events + line joins, newest first
- try {
- const c = await IAP.getConfig();
- const ov = $('ovFeed');
- const rows = [];
- if (d.memberId) {
- const a = await (await fetch('/api/my/activity')).json();
- for (const ev of [...(a.earnings || []), ...(a.purchases || [])]
- .sort((x, y) => y.block - x.block).slice(0, 5)) rows.push(IAP.feedRow(ev, c));
- }
- for (const r of (d.referrals || []).slice(0, 3)) {
- const div = document.createElement('div');
- div.className = 'row';
- div.innerHTML = '🤝 ' + esc(r.name || r.email || 'A new member') + ' joined your line'
- + new Date(r.joined).toLocaleDateString() + '';
- rows.push(div);
- }
- if (rows.length) {
- ov.innerHTML = '';
- rows.slice(0, 6).forEach(r => ov.appendChild(r));
- }
- } catch (e) {}
- // ready-to-send share message + promo tools, personalized
- const link = location.origin + '/join/' + (d.username || d.refCode || d.memberId || '');
- fillPromo(link, d);
- // founding-week readiness: shown until every item is done (or the launch moment is a week past)
- try {
- const cfg = await IAP.getConfig(); const items = IAP.launchChecks(d); const done = items.filter(i => i.done).length;
- const at = cfg.launchAt ? new Date(cfg.launchAt).getTime() : 0;
- const show = done < items.length && !(at && Date.now() > at + 7 * 86400000);
- const lm = $('launchMark');
- if (lm) { lm.hidden = !show; lm.innerHTML = show ? 'Launch ready: ' + done + ' of ' + items.length + '. ' + (at && Date.now() < at ? 'Doors open ' + new Date(at).toLocaleString([], { weekday: 'short', hour: 'numeric', minute: '2-digit' }) + '. ' : '') + 'Open the founding-week checklist' : ''; }
- } catch (e) {}
- // people waiting for a sponsor in the holding tank (Marty, 2026-09-12): every Overview sees it
- try {
- const tw = d.tankWaiting, tn = $('tankNotice');
- if (tn) {
- tn.hidden = !(tw && tw.count);
- if (tw && tw.count) tn.innerHTML = '' + tw.count + (tw.count === 1 ? ' person is' : ' people are') + ' waiting for a sponsor in the holding tank \u00b7 '
- + tw.names.map(esc).join(', ') + (tw.count > tw.names.length ? ' and more' : '') + '. Adopt them from My line'
- + (tw.eligible ? '.' : ' (you need your own $25 package first).')
- + (tw.ready ? ' ' + tw.ready + ' of them ' + (tw.ready === 1 ? 'has' : 'have') + ' linked a wallet and ' + (tw.ready === 1 ? 'is' : 'are') + ' ready to switch on payouts.' : '');
- }
- } catch (e) {}
- if (d.username) { // wall link rides the username
- const wl = location.origin + '/wall/' + d.username;
- $('wallLine').textContent = wl;
- if ($('promoWallStrip')) { // the same wall link at the top of Promo tools, next to the invite link
- $('promoWallStrip').hidden = false; $('promoWallLink').textContent = wl; $('promoWallOpen').href = '/wall/' + d.username;
- $('promoWallCopy').onclick = async () => { try { await navigator.clipboard.writeText(wl); IAP.status('Wall link copied.', 'ok'); } catch (e) { IAP.status('Copy failed. Select the link and copy it.', 'bad'); } };
- }
- $('wallCopy').hidden = false;
- $('wallOpen').hidden = false;
- $('wallOpen').href = '/wall/' + d.username;
- $('wallCopy').onclick = async () => {
- try { await navigator.clipboard.writeText(wl); IAP.status('Wall link copied.', 'ok'); }
- catch (e) { IAP.status('Copy failed. Select the link text instead.', 'bad'); }
- };
- }
- if (d.refCode || d.memberId) {
- const pitch = 'I found an advertising site that pays referrals instantly to your own wallet. '
- + 'No withdrawals, no waiting, and every payment is public on a blockchain ledger you can check yourself. '
- + 'Free to join and look around: ' + link;
- $('copyPitch').hidden = false;
- $('pitchPreview').hidden = false;
- $('pitchPreview').textContent = '"' + pitch + '"';
- $('copyPitch').onclick = async () => {
- try { await navigator.clipboard.writeText(pitch); IAP.status('Message copied. Paste it anywhere.', 'ok'); }
- catch (e) { IAP.status('Copy failed. Select the preview text instead.', 'bad'); }
- };
- }
- } catch (e) {}
- }
-
- // ── back-office menu: hash-routed panes ───────────────
- const PANES = ['overview', 'line', 'pipeline', 'rotator', 'buy', 'campaigns', 'earn', 'earnings', 'promo', 'training', 'wallet', 'profile'];
- const TITLES = { overview: 'Start', line: 'My line', pipeline: 'Pipeline', rotator: 'Rotator', buy: 'Buy packages', campaigns: 'Campaigns',
- earn: 'Earn credits', earnings: 'Earnings', promo: 'Promo tools', training: 'Training',
- wallet: 'Wallet & account', profile: 'Profile' };
- const MOVED = { buy: '/credits', rotator: '/links', campaigns: '/ads', earn: '/ads', earnings: '/credits', wallet: '/wallet' }; // control-room screens (2026-10-08)
- function setPane(name) {
- if (MOVED[name]) { location.replace(MOVED[name]); return; }
- if (!PANES.includes(name)) name = 'overview';
- for (const p of PANES) {
- const el = $('pane-' + p);
- if (el) el.hidden = p !== name;
- }
- document.querySelectorAll('.bo-menu [data-pane]').forEach(b =>
- b.classList.toggle('on', b.dataset.pane === name));
- if ($('boTitle')) $('boTitle').textContent = TITLES[name];
- { const h1 = document.querySelector('.topbar h1'); if (h1 && TITLES[name]) h1.textContent = TITLES[name]; }
- // member ads: a fresh text ad in the strip under the title, and a banner at the foot of the pane
- IAP.adSlot('text', 'adStripTop');
- if ($('adSlotPane-' + name)) IAP.adSlot('banner', 'adSlotPane-' + name);
- if (name === 'earn') setEarnSub(earnSub); // refresh whichever sub-tab is active
- else if (vidState.token) stopVideo();
- if (name === 'profile') loadLineBanner();
- if (name === 'line') { loadLineage(); loadUplineMessages(); loadCoach(); loadLinkStats(); loadProspects(); }
- if (name === 'campaigns') ['cTarget', 'cImage', 'cVideoUrl'].forEach(id => { if ($(id)) $(id).value = ''; }); // no residual URL between visits
- if (name === 'training') loadTraining();
- if (name === 'pipeline') loadPipeline();
- if (name === 'rotator') loadRotator();
- document.getElementById('memberArea').classList.remove('side-open'); // close mobile drawer
- if (location.hash !== '#' + name) history.replaceState(null, '', '#' + name);
- }
- document.querySelectorAll('.bo-menu [data-pane]').forEach(b =>
- b.addEventListener('click', () => setPane(b.dataset.pane)));
- document.querySelectorAll('.qa [data-goto]').forEach(b =>
- b.addEventListener('click', () => setPane(b.dataset.goto)));
- const qaCopy = document.getElementById('qaCopyInvite');
- if (qaCopy) qaCopy.addEventListener('click', async () => {
- const link = document.getElementById('inviteLine').textContent;
- if (!link || !link.startsWith('http')) { setPane('line'); return; }
- try { await navigator.clipboard.writeText(link); IAP.status('Invite link copied.', 'ok'); }
- catch (e) { setPane('line'); }
- });
- window.addEventListener('hashchange', () => setPane(location.hash.slice(1)));
- if ($('boBurger')) $('boBurger').addEventListener('click', () =>
- document.getElementById('memberArea').classList.toggle('side-open'));
-
- async function render() {
- // while /api/me answers, show a spinner instead of flashing the sign-in card at a signed-in member
- let me = null;
- try { me = await IAP.refreshNavWallet(); } catch (e) { me = null; }
- if ($('bootSpin')) $('bootSpin').hidden = true;
- // one way in: email. A wallet-only session (no account) is sent back to the
- // email card with a finish-setup note; verifying the code links that wallet.
- const walletOnly = !!(me && me.signedIn && !me.email);
- const signedIn = me && me.signedIn && !walletOnly;
- // signed out: the Control Room sign-in dialog (the old email card only serves the wallet-only finish-setup case)
- $('authArea').hidden = !!signedIn || !walletOnly;
- $('memberArea').hidden = !signedIn;
- if ($('mcFinish')) $('mcFinish').hidden = !walletOnly;
- if (!signedIn && !walletOnly && window.CR) { // the Control Room shell runs the sign-in dialog; render again once it reports a session
- if (window.LS_SESSION_READY && (render.retries = (render.retries || 0) + 1) < 6) { setTimeout(render, 400); }
- else if (!render.waiting) { render.waiting = true; window.addEventListener('ls:session', () => { render.waiting = false; render(); }, { once: true }); }
- }
- if (!signedIn) return;
- TANK_HOLD = (!me.memberId && me.tankHold) || null;
- if ($('adminLink')) $('adminLink').hidden = !me.isAdmin; // admin portal link, only for ADMIN_EMAIL
- // REQUIRED first step (Marty, 2026-09-12): no username, nothing else. The modal cannot be
- // skipped or dismissed; it resolves only when a username is saved, then the area renders.
- if (!me.username) {
- if (!render.gating) { render.gating = true; showOnboard(true).then(() => { render.gating = false; render(); }); }
- return;
- }
- // arrived from an invite page: run the welcome tour and login ad once
- if (/[?&]welcome=1/.test(location.search) && !render.welcomed) {
- render.welcomed = true;
- history.replaceState(null, '', '/tools' + (location.hash || ''));
- (async () => {
- try { if (!(await showGauntlet())) await showLoginAd(); } catch (e) {}
- await render();
- })();
- }
- setPane(location.hash.slice(1) || 'overview');
- $('campGate').hidden = !!me.memberId;
- $('earnGate').hidden = !!me.memberId;
- if (me.username && !me.address) { let shown = ''; try { shown = sessionStorage.getItem('iap.gs.walletHint'); sessionStorage.setItem('iap.gs.walletHint', '1'); } catch (e) {} if (shown !== '1') setTimeout(() => IAP.status('Next step when you are ready: link your wallet so your payouts have somewhere to land. The Getting started card at the top shows how.', 'ok'), 1200); }
- loadDashboard();
-
- const who = [];
- if (me.email) who.push(me.email);
- // members kept asking whether the wallet was really connected (Marty, 2026-09-12): say it, with a green check
- if (me.address) who.push('✓Wallet connected' + me.address.slice(0, 8) + '…' + me.address.slice(-6) + '');
- else who.push('!No wallet connected yet(link one below)');
- if (me.memberId) who.push('on-chain member #' + me.memberId + ''
- + (me.onchainSponsorId ? ', sponsored by #' + me.onchainSponsorId : ''));
- else if (me.sponsorId && !TANK_HOLD) who.push('invited by member #' + me.sponsorId);
- $('posLine').innerHTML = who.join(' ');
-
- $('creditLine').textContent = (me.credits || 0).toLocaleString();
- loadPositions(me);
- $('linkCard').hidden = !!me.address;
- $('activateCard').hidden = !(me.address && !me.memberId);
- { let hn = $('tankHoldNote'); // held for an adopter: say so, and no activate button
- if (!hn) { hn = document.createElement('p'); hn.id = 'tankHoldNote'; hn.className = 'small'; hn.style.cssText = 'margin:8px 0 0;color:var(--ok)'; $('activateBtn').insertAdjacentElement('beforebegin', hn); }
- hn.hidden = !TANK_HOLD; hn.textContent = TANK_HOLD ? tankHoldText(TANK_HOLD) : ''; $('activateBtn').hidden = !!TANK_HOLD; }
- $('activityArea').hidden = !me.memberId;
- $('campGate').hidden = true; // earned credits fund campaigns for everyone
- $('campaignCard').hidden = false;
- loadCampaigns();
-
- // profile pane state
- $('pfCurrent').textContent = me.username ? '@' + me.username + ' is your permanent username. Your invite link, your public page and any banners you shared carry it, so it cannot be changed.' : 'No username yet. Members see you as a number until you pick one. Choose carefully: it is permanent once saved.';
- if (!$('pfUsername').value) $('pfUsername').value = me.username || '';
- $('pfUsername').disabled = !!me.username; $('pfSaveBtn').hidden = !!me.username;
- $('pfDetails').innerHTML = 'Email: ' + (me.email || 'none') + ' Wallet: '
- + (me.address ? '' + me.address.slice(0, 10) + '…' + me.address.slice(-6) + '' : 'not linked yet')
- + ' On-chain member: ' + (me.memberId ? '#' + me.memberId : 'not yet');
- // the share link works from day one; usernames make it a vanity link
- if (me.username || me.refCode || me.memberId) {
- $('inviteLine').textContent = location.origin + '/join/' + (me.username || me.refCode || me.memberId);
- $('copyInvite').hidden = false;
- } else {
- $('inviteLine').textContent = 'Sign in with your email to get your link.';
- $('copyInvite').hidden = true;
- }
- if (me.memberId) {
- const bc = me.buyerCount || 0;
- $('qualLine').innerHTML = '' + bc + ' qualifying buyer(s) referred '
- + (bc >= 5 ? 'Level 3 unlocked: full three-level earnings'
- : bc >= 2 ? 'Level 2 unlocked · ' + (5 - bc) + ' more for level 3'
- : (2 - bc) + ' more buyer(s) of $25+ unlock level 2');
- loadActivity();
- } else {
- $('qualLine').innerHTML = 'Share your link now. Then switch on payouts (free, above) '
- + 'before your people start buying: the contract locks each buyer to their sponsor at '
- + 'their first purchase, and payments only route to wallets that are switched on.';
- }
- }
-
- async function loadActivity() {
- try {
- const c = await IAP.getConfig();
- const a = await (await fetch('/api/my/activity')).json();
- const fill = (id, evs, empty) => {
- const el = $(id);
- el.innerHTML = '';
- if (!evs || !evs.length) { el.innerHTML = '
' + empty + '
'; return; }
- for (const ev of evs) el.appendChild(IAP.feedRow(ev, c));
- };
- fill('earnFeed', a.earnings, 'No payouts yet. They appear here the moment one lands.');
- fill('refFeed', a.referrals, 'No referral activity yet. Share your invite link.');
- fill('buyFeed', a.purchases, 'No purchases from your wallet yet.');
- } catch (e) {}
- }
-
- async function loadCampaigns() {
- try {
- const r = await (await fetch('/api/my/campaigns')).json();
- if (r.error) return;
- lastRates = r.rates; lastSlots = r.loginSlots || null;
- if ($('cGeoHint') && r.tiers) $('cGeoHint').textContent = 'All three ticked = everyone. Tier 1: ' + r.tiers.t1.join(', ') + '. Tier 2: ' + r.tiers.t2.join(', ') + '. Tier 3: every other country. Geo applies to delivery on this site; a narrowed banner or text ad is kept off the worldwide partner network. ' + (r.geoReady ? '' : 'Country data is still loading, so narrowed campaigns pause until it is ready. ') + 'IP geolocation by DB-IP.';
- // populate the banner-size dropdown once (ids map to NAS width/height)
- if (r.bannerSizes && $('cSize') && !$('cSize').options.length)
- $('cSize').innerHTML = r.bannerSizes.map(s => '').join('');
- applyType(); // the default type is banner: show its size + image rows now that the sizes exist
- soloHint();
- if ($('spendBanner')) {
- $('spendBanner').hidden = false;
- $('spendBig').textContent = r.availableCredits.toLocaleString();
- $('spendSub').textContent = '= $' + (r.availableCredits / 100).toLocaleString(undefined, { maximumFractionDigits: 2 }) + ' of ad delivery · ' + r.purchasedCredits.toLocaleString() + ' purchased' + (r.creditedCredits ? ' (' + r.creditedCredits.toLocaleString() + ' of it credited to you, spends on anything)' : '') + ' + ' + (r.earnedCredits || 0).toLocaleString() + ' earned' + (r.positionCount > 1 ? ' · pooled across ' + r.positionCount + ' positions (largest single position ' + (r.largestPosition || 0).toLocaleString() + ')' : '');
- if ($('spendNote')) $('spendNote').textContent = r.inCampaigns
- ? 'Not counting ' + r.inCampaigns.toLocaleString() + ' credits already set aside for your live campaigns. That budget spends down inside each campaign below. This number only moves when you start, top up or pause a campaign.'
- : 'This is what is not committed to a campaign. When you start one, its budget moves out of here and spends down inside the campaign.';
- $('spendRates').innerHTML = [['Banner', r.rates.bannerCreditsPerBatch + ' cr / ' + r.rates.bannerBatch + ' views'], ['Text', r.rates.textCreditsPerBatch + ' cr / ' + r.rates.textBatch + ' views'], ['Login', (r.rates.loginSlotCredits || 1000).toLocaleString() + ' cr / ' + (r.rates.loginSlotDays || 30) + '-day slot'], ['Solo', r.rates.soloCostPerRecipient + ' cr / delivery'], ['Featured', (r.rates.featuredPerDay || 40) + ' cr / day'], ['Visit', (r.rates.visitCostPerVisit || 3) + ' cr / visit']].map(x => '' + x[0] + ' ' + x[1] + '').join('');
- }
- $('rateLine').textContent = 'Available to spend: ' + r.availableCredits.toLocaleString()
- + (r.earnedCredits ? ' (' + r.purchasedCredits.toLocaleString() + ' purchased + ' + r.earnedCredits + ' earned)' : '')
- + (r.inCampaigns ? ' · ' + r.inCampaigns.toLocaleString() + ' set aside in live campaigns' : '')
- + ' credits · rates: banner ' + r.rates.bannerCreditsPerBatch + 'cr/' + r.rates.bannerBatch
- + ' views, text ' + r.rates.textCreditsPerBatch + 'cr/' + r.rates.textBatch
- + ' views, login ' + (r.rates.loginSlotCredits || 1000) + 'cr per ' + (r.rates.loginSlotDays || 30) + '-day slot, solo '
- + (r.rates.soloCostPerRecipient || 5) + 'cr/delivery';
- const el = $('campList');
- el.innerHTML = '';
- if (!r.campaigns.length) { el.innerHTML = '
No campaigns yet. Launch your first below.
'; return; }
- const tbl = document.createElement('div');
- tbl.className = 'tablewrap';
+ const CH = new Proxy({}, { get: (_, k) => { const cs = getComputedStyle(document.documentElement); const v = { mint: '--mint', cyan: '--cyan', violet: '--violet', amber: '--amber', track: '--muted-soft' }[k]; return (v && cs.getPropertyValue(v).trim()) || { mint: '#3b9dff', cyan: '#54ccff', violet: '#9d7dff', amber: '#ffb238', track: 'rgba(139,166,156,.18)' }[k]; } });
+ function bars(el, xel, data) { // data: [{v,label,tip,alt}]
+ if (!el) return;
+ const max = Math.max(1, ...data.map(d => d.v));
+ el.innerHTML = data.length
+ ? data.map(d => '').join('')
+ : ''.repeat(8);
+ if (xel) xel.innerHTML = data.map(d => '' + esc(d.label) + '').join('');
+ }
+ function donut(el, segs, center) { // segs sum to the ring; r=15.9155 → circumference 100
+ if (!el) return;
+ const total = segs.reduce((s, x) => s + x.v, 0);
+ let off = 25, out = '';
+ if (total > 0) for (const s of segs) {
+ const len = s.v / total * 100;
+ if (len <= 0 || s.color === 'none') { off -= Math.max(0, len); continue; }
+ out += '';
+ off -= len;
+ }
+ out += '' + esc(center.big) + ''
+ + '' + esc(center.small) + '';
+ el.innerHTML = out;
+ }
+ function legend(el, rows) {
+ if (el) el.innerHTML = rows.map(r => '
'
+ + esc(r.label) + ' ' + esc(r.v) + '
').join('');
+ }
+ async function loadCharts(d) {
+ // credit composition donut + today's viewing ring (live balances)
+ try {
+ const st = await (await fetch('/api/my/earn')).json();
+ if (!st.error) {
+ // one rule: a balance is what is NOT committed to a live campaign. Budgets are
+ // set aside when a campaign starts and spend down inside Campaigns, so these
+ // numbers only move when a campaign is created, topped up or paused
+ const purchased = d.credits || 0, earned = d.earnedCredits != null ? d.earnedCredits : (st.earnedAvailable != null ? st.earnedAvailable : (st.earned || 0)), inC = d.inCampaigns || 0;
+ $('dbCredits').textContent = (purchased + earned).toLocaleString();
+ // the Wallet tab card showed on-chain credits only, so promo/earned credits looked like 0 there (Jim, 2026-09-13)
+ if ($('creditLine')) $('creditLine').innerHTML = (purchased + earned).toLocaleString() + ' ' + purchased.toLocaleString() + ' purchased · ' + earned.toLocaleString() + ' earned';
+ $('dbCreditsSub').textContent = purchased.toLocaleString() + ' purchased' + (d.creditedCredits ? ' (' + d.creditedCredits.toLocaleString() + ' credited to you)' : '') + ' · ' + earned.toLocaleString() + ' earned' + (inC ? ' · ' + inC.toLocaleString() + ' in campaigns' : '');
+ donut($('chDonut'),
+ [{ v: purchased, color: CH.mint }, { v: earned, color: CH.cyan }, { v: inC, color: CH.amber }],
+ { big: (purchased + earned).toLocaleString(), small: 'available' });
+ legend($('chDonutLegend'), [
+ { color: CH.mint, label: 'Purchased, available', v: purchased.toLocaleString() },
+ { color: CH.cyan, label: 'Earned, available', v: earned.toLocaleString() },
+ { color: CH.amber, label: 'In live campaigns', v: inC.toLocaleString() }]);
+ const done = Math.min(st.views || 0, st.target || 5), left = Math.max(0, (st.target || 5) - done);
+ donut($('chRing'), [{ v: done, color: st.claimed ? CH.mint : CH.cyan }, { v: left, color: 'none' }],
+ { big: done + '/' + (st.target || 5), small: st.claimed ? 'claimed' : 'ads viewed' });
+ legend($('chRingLegend'), [
+ { color: st.claimed ? CH.mint : CH.cyan, label: 'Viewed today', v: done },
+ { color: CH.track, label: 'To go', v: left },
+ { color: CH.amber, label: 'Claim pays', v: '+' + (st.claimCredits || 0) + ' credits' }]);
+ }
+ } catch (e) {}
+ // recent on-chain payouts, sized to scale, oldest→newest
+ try {
+ let evs = [];
+ if (d.memberId) {
+ const a = await (await fetch('/api/my/activity')).json();
+ evs = (a.earnings || []).filter(e => e.amountWei).sort((x, y) => x.block - y.block).slice(-12);
+ }
+ bars($('chEarnBars'), $('chEarnX'), evs.map(e => ({
+ v: Number(BigInt(e.amountWei) / 1000000000000n) / 1e6,
+ label: e.type === 'AwardPaid' ? 'award' : 'L' + (e.tier || 1),
+ tip: IAP.fmtPol(e.amountWei) + ' POL', alt: e.type === 'AwardPaid' })));
+ if (!evs.length) $('chEarnSub').textContent = d.memberId
+ ? 'no payouts yet — share your link' : 'activate a package to start earning';
+ } catch (e) {}
+ // campaign delivery: impressions per campaign
+ try {
+ const r = await (await fetch('/api/my/campaigns')).json();
+ const cs = (r.campaigns || []).slice(0, 8);
+ bars($('chCampBars'), $('chCampX'), cs.map(c => ({
+ v: c.imps || 0, label: String(c.name || c.type).slice(0, 9),
+ tip: (c.name || c.type) + ': ' + (c.imps || 0) + ' imps · ' + (c.clicks || 0) + ' clicks',
+ alt: c.type === 'text' })));
+ if (!cs.length) $('chCampSub').textContent = 'no campaigns yet — place your first ad';
+ } catch (e) {}
+ }
+ // ── live updates: subscribe to the chain event stream so the members area
+ // reacts to on-chain changes (payouts, qualifications) without a refresh ──
+ let MYID = 0;
+ // synthesized sounds (no asset files; CSP-safe). cha-ching on a payment, pop on a message.
+ function playSound(kind) {
+ try {
+ const AC = window.AudioContext || window.webkitAudioContext; if (!AC) return;
+ const ctx = window.__iapAC || (window.__iapAC = new AC());
+ if (ctx.state === 'suspended') ctx.resume();
+ const now = ctx.currentTime;
+ const tone = (freq, at, dur, type, peak) => {
+ const o = ctx.createOscillator(), g = ctx.createGain();
+ o.type = type || 'sine'; o.frequency.value = freq;
+ g.gain.setValueAtTime(0.0001, now + at);
+ g.gain.exponentialRampToValueAtTime(peak || 0.22, now + at + 0.02);
+ g.gain.exponentialRampToValueAtTime(0.0001, now + at + dur);
+ o.connect(g).connect(ctx.destination); o.start(now + at); o.stop(now + at + dur + 0.02);
+ };
+ if (kind === 'chaching') { tone(1318, 0, 0.34, 'sine', 0.25); tone(1760, 0.09, 0.4, 'sine', 0.25); }
+ else { tone(680, 0, 0.16, 'triangle', 0.18); tone(1020, 0.05, 0.16, 'triangle', 0.16); }
+ } catch (e) {}
+ }
+ function startLiveFeed() {
+ if (window.__iapFeed || !window.EventSource) return;
+ try {
+ const es = new EventSource('/api/feed/live');
+ window.__iapFeed = es;
+ es.onmessage = m => { let ev; try { ev = JSON.parse(m.data); } catch (e) { return; } handleLiveEvent(ev); };
+ // browser auto-reconnects on error; nothing to do
+ } catch (e) {}
+ }
+ let liveRefreshT = null;
+ function liveRefresh() { // debounce a burst of events into one refresh
+ clearTimeout(liveRefreshT);
+ liveRefreshT = setTimeout(() => { loadDashboard(); try { loadLineage(); } catch (e) {} }, 600);
+ }
+ // community toasts (Marty, 2026-09-12: keep the dashboard feeling alive): everyone else's joins,
+ // purchases, payouts, qualifications, tank arrivals and adoptions, in a second, quieter toast so
+ // they never replace a personal one. At most one every 4 s; a burst shows the latest.
+ let liveT = 0, liveQ = null;
+ function communityToast(msg) {
+ const now = Date.now();
+ if (now - liveT < 4000) { liveQ = msg; if (!communityToast._q) communityToast._q = setTimeout(() => { communityToast._q = null; const m = liveQ; liveQ = null; if (m) communityToast(m); }, 4200 - (now - liveT)); return; }
+ liveT = now;
+ let el = document.getElementById('liveToast');
+ if (!el) { el = document.createElement('div'); el.id = 'liveToast'; el.setAttribute('role', 'status'); el.style.cssText = 'position:fixed;left:16px;bottom:16px;z-index:90;max-width:min(360px,calc(100vw - 32px));background:var(--panel-solid);border:1px solid var(--line-strong);border-left:3px solid var(--mint);border-radius:12px;padding:10px 14px;font-size:14px;box-shadow:0 10px 30px rgba(0,0,0,.4);transition:opacity .3s'; document.body.appendChild(el); }
+ el.textContent = msg; el.hidden = false; el.style.opacity = '1';
+ clearTimeout(communityToast._t); communityToast._t = setTimeout(() => { el.style.opacity = '0'; setTimeout(() => { el.hidden = true; }, 350); }, 6000);
+ }
+ function handleLiveEvent(ev) {
+ if (!ev || !ev.type) return;
+ const nm = id => (ev.names && ev.names[id]) ? '@' + ev.names[id] : 'member #' + id;
+ // site-wide activity (not about me): joins, tank, adoptions, purchases, payouts, qualifications
+ if (ev.type === 'Joined') { communityToast('👋 ' + ev.name + ' just joined' + (ev.tank ? ' and is waiting for a sponsor in the holding tank' : '')); liveRefresh(); return; }
+ if (ev.type === 'Adopted') { communityToast('🤝 ' + ev.sponsor + ' picked up ' + ev.member + ' from the holding tank'); liveRefresh(); return; }
+ if (ev.type === 'Contest') { communityToast('🏆 ' + ev.winner + ' won the ' + (ev.kind === 'week' ? 'weekly' : 'monthly') + ' referral contest'); return; }
+ if (ev.type === 'Badge') { communityToast('🏆 ' + ev.member + ' unlocked ' + ev.label); return; }
+ if (ev.type === 'Released') { communityToast('🪣 ' + ev.sponsor + ' returned ' + ev.member + ' to the holding tank'); liveRefresh(); return; }
+ const mine = MYID && (ev.recipientId === MYID || ev.toId === MYID || ev.sponsorId === MYID || ev.skippedId === MYID || ev.buyerId === MYID);
+ if (!mine) {
+ if (ev.type === 'Purchase' && ev.buyerId) communityToast('🧾 ' + nm(ev.buyerId) + ' just bought a $' + Math.round((ev.priceCents || 0) / 100) + ' package');
+ else if (ev.type === 'TierPaid' && ev.recipientId) communityToast('💸 ' + nm(ev.recipientId) + ' just got paid ' + IAP.fmtPol(ev.amountWei) + ' POL');
+ else if (ev.type === 'BuyerCounted' && ev.sponsorId) communityToast('🎯 ' + nm(ev.sponsorId) + ' now has ' + ev.newCount + ' qualifying buyer' + (ev.newCount === 1 ? '' : 's'));
+ else if (ev.type === 'MemberActivated' && ev.id) communityToast('⚡ ' + nm(ev.id) + ' switched on payouts');
+ return;
+ }
+ if (!MYID) return;
+ let toast = null, kind = 'ok';
+ let sound = null;
+ if (ev.type === 'TierPaid' && ev.recipientId === MYID) { toast = '💸 You earned a level-' + ev.tier + ' payout of ' + IAP.fmtPol(ev.amountWei) + ' POL!'; sound = 'chaching'; }
+ else if (ev.type === 'AwardPaid' && ev.toId === MYID) { toast = '💸 You received ' + IAP.fmtPol(ev.amountWei) + ' POL!'; sound = 'chaching'; }
+ else if (ev.type === 'BuyerCounted' && ev.sponsorId === MYID) toast = '🎯 A referral just qualified — you now have ' + ev.newCount + ' qualifying buyer' + (ev.newCount === 1 ? '' : 's') + '!';
+ else if (ev.type === 'PassedUp' && ev.skippedId === MYID) { toast = '⚠️ A level-' + ev.tier + ' payout passed you by. Get qualified to catch these.'; kind = 'bad'; }
+ else if (ev.type === 'Purchase' && ev.buyerId === MYID) toast = '✅ Purchase settled on-chain — your credits are updated.';
+ else if (ev.type === 'MemberActivated' && ev.sponsorId === MYID) toast = '🤝 A new member just activated in your line!';
+ if (toast) { IAP.status(toast, kind); if (sound) playSound(sound); liveRefresh(); }
+ }
+
+ // training center: videos + materials (admin-curated via data/training.json)
+ async function loadTraining() {
+ try {
+ const r = await (await fetch('/api/training')).json();
+ const el = $('trainingList'); if (!el) return;
+ const items = r.items || [];
+ if (!items.length) { el.innerHTML = '
Training materials are being added. Check back soon.
'; return; }
+ // section pills at the top: one per group, plus All; the active pill filters the list
+ const groups = [...new Set(items.map(it => it.group).filter(Boolean))];
+ const pills = $('trainingPills');
+ const want = loadTraining.filter || 'all';
+ if (pills) {
+ pills.hidden = groups.length < 2;
+ pills.innerHTML = ['all', ...groups].map(g => '').join('');
+ pills.querySelectorAll('[data-tg]').forEach(b => b.addEventListener('click', () => { loadTraining.filter = b.dataset.tg; loadTraining(); }));
+ }
+ const shown = want === 'all' ? items : items.filter(it => it.group === want);
+ let lastGroup = null;
+ el.innerHTML = shown.map(it => {
+ // optional section header: entries carry a `group`; a header renders when it changes
+ let head = '';
+ if (it.group && it.group !== lastGroup) { lastGroup = it.group; head = '
' + esc(it.group) + '
'; }
+ const isVid = it.videoUrl && /\.(mp4|webm)(\?|$)/i.test(it.videoUrl);
+ // poster: the admin list can carry one; otherwise assume a .jpg next to the .mp4 (the pipeline uploads both)
+ const poster = it.posterUrl || (isVid ? it.videoUrl.replace(/\.(mp4|webm)(\?.*)?$/i, '.jpg$2') : '');
+ const media = isVid ? '' : '';
+ const links = [];
+ if (it.videoUrl && !isVid) links.push('Watch');
+ if (it.docUrl) links.push('Open material');
+ return head + '
' + esc(it.title || 'Lesson') + '
'
+ + (it.desc ? '
' + esc(it.desc) + '
' : '') // pre-line: a written lesson keeps its paragraphs (Banner Spin, 2026-10-20)
+ + (media ? '
' + media + '
' : '')
+ + (links.length ? '
' + links.join(' ') + '
' : '') + '
';
+ }).join('');
+ } catch (e) {}
+ }
+ // visual line tree on the Overview: YOU + three levels, qualified directs in gold
+ async function loadLineTree(buyerCount) {
+ try {
+ const r = await (await fetch('/api/my/line')).json();
+ const el = $('lineTree'); if (!el) return;
+ const levels = r.levels || [];
+ const total = levels.reduce((n, L) => n + L.members.length, 0);
+ if ($('treeSub')) $('treeSub').textContent = total ? total + ' across 3 levels' : 'share your link to grow';
+ const chip = (m, q) => '' + esc(String(m.name || 'M').replace(/^@/, '').slice(0, m.own ? 20 : 14)) + (m.buyers ? '' + m.buyers + '' : '') + '';
+ const rowFor = lvl => {
+ const L = levels.find(x => x.level === lvl); const members = L ? L.members : [];
+ // gold = the contract counted this member as one of your qualifying buyers (not "the first N chips")
+ let html = members.map(m => chip(m, !!(m.qualified || m.bought))).join(''); // gold on every level = made their $25+ buy
+ if (lvl <= 2 && members.length < (lvl === 1 ? 2 : 4)) html += '+ open';
+ if (!html) html = '+ open';
+ return '
L' + lvl + '
' + html + '
';
+ };
+ el.innerHTML = '
YOU
' + rowFor(1) + rowFor(2) + rowFor(3);
+ } catch (e) {}
+ }
+ // "What's new" card: latest notes + what is being built; a dot marks notes newer than the member's last look (Marty, 2026-09-14)
+ let newsLoaded = false;
+ async function loadNews() {
+ if (newsLoaded || !$('newsCard')) return; newsLoaded = true;
+ try {
+ const r = await (await fetch('/api/releases')).json();
+ if (!r.notes.length && !r.roadmap.length) return;
+ let seen = ''; try { seen = localStorage.getItem('iap.news.seen') || ''; } catch (e) {}
+ const esc = t => String(t == null ? '' : t).replace(/[&<>"]/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"' }[c]));
+ const notes = r.notes.slice(0, 3).map(n => '
').join('');
+ const copy = {
+ user: ['Pick your username', 'It becomes your invite link and your public page, and it is permanent.', 'Choose a username', () => showOnboard(true)],
+ wallet: ['Link your wallet', 'Your payouts land in a wallet you control, so the site needs to know which one is yours. One free signature, no purchase. MetaMask recommended; Phantom users switch Polygon on first. Never held crypto? The wallet guide walks you through it.', 'Link my wallet', () => jumpTo('wallet', 'linkBtn')],
+ payouts: ['Switch on payouts', 'One small transaction registers your wallet with the contract so commissions can reach it. Buying any package does this automatically.', 'Activate payouts', () => jumpTo('wallet', 'activateBtn')],
+ package: ['Your first package', 'From $10. The $25 package is the one that counts you as a qualifying buyer for your sponsor and unlocks adopting from the holding tank.', 'See packages', () => jumpTo('buy', null)]
+ }[cur.k];
+ if (cur.k === 'payouts' && TANK_HOLD) { copy[0] = 'Matching you with a sponsor'; copy[1] = tankHoldText(TANK_HOLD); copy[2] = null; } // no activate button while held
+ $('gsNow').innerHTML = '
';
- el.appendChild(tbl);
- el.querySelectorAll('button[data-camp]').forEach(b => b.addEventListener('click', async () => {
- try { await api('/api/my/campaigns/' + b.dataset.camp + '/' + b.dataset.act); await loadCampaigns(); }
- catch (e) { IAP.status(e.message, 'bad'); }
- }));
- el.querySelectorAll('button[data-topup]').forEach(b => b.addEventListener('click', async () => {
- const n = await IAP.ask({ title: 'Add credits', text: 'How many credits to add to this campaign? More credits buy more views.', type: 'number', placeholder: 'e.g. 100', ok: 'Add credits' });
- if (!n) return;
- try { const r = await api('/api/my/campaigns/' + b.dataset.topup + '/topup', { credits: Number(n) });
- IAP.status('Added ' + r.added + ' credits' + (r.reactivated ? ' — campaign is live again.' : '.'), 'ok');
- await loadCampaigns(); loadDashboard();
- } catch (e) { IAP.status(e.message, 'bad'); }
- }));
- } catch (e) {}
- }
- let lastRates = null, lastSlots = null;
- function soloHint() {
- if (!lastRates || $('cType').value !== 'solo') return;
- const cost = lastRates.soloCostPerRecipient || 5;
- const n = Math.floor((Number($('cBudget').value) || 0) / cost);
- $('cSoloHint').textContent = cost + ' credits per guaranteed inbox delivery'
- + (n ? ' — this budget reaches ' + n + ' members' : '')
- + '. Readers earn ' + (lastRates.soloReadCredits || 2) + ' credits for a real read, so your message gets opened.';
- }
- $('cBudget').addEventListener('input', soloHint);
- // rich solo editor: small toolbar over contenteditable (CSP allows no external editor);
- // the server whitelist-sanitizes whatever HTML arrives, this is just authoring comfort
- document.querySelectorAll('.ed-bar [data-cmd]').forEach(btn =>
- btn.addEventListener('click', () => { $('cSoloEd').focus(); document.execCommand(btn.dataset.cmd, false, null); }));
- document.querySelectorAll('.ed-bar [data-block]').forEach(btn =>
- btn.addEventListener('click', () => { $('cSoloEd').focus(); document.execCommand('formatBlock', false, btn.dataset.block); }));
- $('edLinkBtn').addEventListener('click', async () => {
- const sel = window.getSelection(); const range = sel && sel.rangeCount ? sel.getRangeAt(0).cloneRange() : null; // the dialog steals the selection
- const url = await IAP.ask({ title: 'Insert link', text: 'Link URL (https://…)', placeholder: 'https://', ok: 'Insert' });
- if (!url) return;
- $('cSoloEd').focus(); if (range) { sel.removeAllRanges(); sel.addRange(range); }
- document.execCommand('createLink', false, url);
- });
- // inline media: upload, then drop the element at the cursor (BV-style)
- let mediaMode = 'image';
- function insertHtmlAtCursor(html) {
- const ed = $('cSoloEd');
- ed.focus();
- if (!document.execCommand('insertHTML', false, html)) ed.insertAdjacentHTML('beforeend', html);
- }
- $('edImgBtn').addEventListener('click', () => { mediaMode = 'image'; $('cSoloFile').accept = 'image/png,image/jpeg,image/webp,image/gif'; $('cSoloFile').click(); });
- $('edVidBtn').addEventListener('click', () => { mediaMode = 'video'; $('cSoloFile').accept = 'video/mp4,video/webm'; $('cSoloFile').click(); });
- $('cSoloFile').addEventListener('change', async () => {
- const f = $('cSoloFile').files[0];
- if (!f) return;
- $('edMediaInfo').textContent = 'Uploading ' + f.name + '…';
- try {
- const r = await (await fetch('/api/my/upload', { method: 'POST', headers: { 'Content-Type': f.type }, body: f })).json();
- if (r.error) { $('edMediaInfo').textContent = r.error; $('cSoloFile').value = ''; return; }
- insertHtmlAtCursor(r.type === 'video'
- ? '
'
- : '
');
- $('edMediaInfo').textContent = f.name + ' inserted';
- } catch (e) { $('edMediaInfo').textContent = 'Upload failed. Try again.'; }
- $('cSoloFile').value = '';
- });
- // raw-text toggle: swap the WYSIWYG surface for the underlying HTML and back
- $('edRawBtn').addEventListener('click', () => {
- const ed = $('cSoloEd'), raw = $('cSoloRaw');
- if (raw.hidden) { raw.value = ed.innerHTML; raw.hidden = false; ed.hidden = true; $('edRawBtn').textContent = 'Visual'; }
- else { ed.innerHTML = raw.value; ed.hidden = false; raw.hidden = true; $('edRawBtn').textContent = 'Raw text'; }
- });
- const WHERE = { banner: 'Runs in the ad viewer, on the home page, the live ledger, every Overview, the sidebar tile, and out in the Network Ad Space rotation across the wider network.',
- text: 'Runs in the ad viewer, the live ledger text slot, and out in the Network Ad Space rotation.',
- login: 'Full screen for every member who signs in, ten seconds, once a day per member. Opens in a fresh tab, so any working page qualifies. A slot is 1,000 purchased credits for 30 days of unlimited sign-in impressions, never charged per day. 3 slots at a time, first come first served. Login ads spend purchased credits only.',
- solo: 'Delivered into member inboxes under Earn credits. Each read is timed and rewarded, so it gets opened.',
- video: 'Plays in Watch videos and the Shorts feed under Earn credits. You pay only for completed watches.',
- featured: 'Your headline and link in the Featured strip on every member Overview for the days you book.',
- visits: 'A distinct member opens your site in a new tab, stays eight seconds and passes a check. Nobody counts twice.' };
- const whereHint = () => { const el = $('cWhere'); if (!el) return; const t = $('cType').value; let s = WHERE[t] || '';
- if (t === 'login' && lastRates) s = s.replace('1,000', (lastRates.loginSlotCredits || 1000).toLocaleString()).replace('30 days', (lastRates.loginSlotDays || 30) + ' days').replace('3 slots', (lastRates.loginSlotsMax || 3) + ' slots');
- if (t === 'login' && lastSlots) s += lastSlots.free ? ' ' + lastSlots.free + ' of ' + lastSlots.max + ' slots open right now.' : ' All ' + lastSlots.max + ' slots are taken right now. You can reserve the next one on the Ads screen (' + location.origin + '/ads): pay now, it starts when a slot frees, and a cancel before then refunds in full.';
- el.textContent = s; };
- whereHint();
- // runs on every type change AND once at load, so the default type (banner) shows its size + image rows immediately
- function applyType() { // hoisted: loadCampaigns may run before this line is reached
- whereHint();
- const t = $('cType').value;
- $('cImageRow').hidden = t !== 'banner'; // only banners carry a creative; login frames its URL
- $('cSizeRow').hidden = t !== 'banner';
- $('cTitleRow').hidden = t !== 'text' && t !== 'solo';
- $('cBodyRow').hidden = t !== 'text';
- $('cSoloRow').hidden = t !== 'solo';
- $('cSoloHint').hidden = t !== 'solo';
- $('cVideoRow').hidden = t !== 'video';
- $('cFeaturedRow').hidden = t !== 'featured';
- $('cVisitsRow').hidden = t !== 'visits';
- if ($('cSchedRow')) { $('cSchedRow').hidden = t === 'featured'; $('cStartLbl').textContent = t === 'solo' ? 'Send from (optional)' : 'Start (optional)';
- $('cSchedHint').textContent = t === 'solo' ? 'Deliveries to member inboxes begin at the time you pick, so you can land when people are reading. Leave empty to start now.' : 'Leave both empty to start now and run until the budget is spent. Times are your local time. Anything left when a campaign ends goes back to Available.'; }
- // fixed-cost types derive their spend (featured = day slots, visits = flat pack),
- // so hide the free-form Budget field for them to avoid confusion
- $('cBudgetRow').hidden = (t === 'featured' || t === 'visits');
- if ($('cCapRow')) $('cCapRow').hidden = !(t === 'banner' || t === 'text');
- // solo ads have a real floor (5cr x 10 deliveries): default to 50 so 10 isn't rejected
- if (t === 'solo' && (!$('cBudget').value || Number($('cBudget').value) < 50)) $('cBudget').value = (lastRates && lastRates.soloCostPerRecipient ? lastRates.soloCostPerRecipient : 5) * 10;
- if (t === 'visits') visitHint();
- if (t === 'login') $('cBudget').value = (lastRates && lastRates.loginSlotCredits) || 1000; // a slot is one flat price
- $('cTitle').placeholder = t === 'solo' ? 'Subject line (max 80)' : 'Headline (max 60)';
- soloHint();
- if (t === 'video') videoHint();
- if (t === 'featured') featHint();
- }
- $('cType').addEventListener('change', applyType);
- let featStartDay = 0; // selected start-day offset (0 = today)
- async function featHint() {
- if (!lastRates || !lastRates.featuredDurations) return;
- if ($('cFeatDays') && !$('cFeatDays').options.length)
- $('cFeatDays').innerHTML = lastRates.featuredDurations.map(dys =>
- '').join('');
- let s = null;
- try { s = await (await fetch('/api/featured/stats')).json(); } catch (e) {}
- if (s && s.occupancy) {
- const grid = $('cFeatDaysGrid');
- grid.innerHTML = s.occupancy.map(d => {
- const label = d.offset === 0 ? 'Today' : d.offset === 1 ? 'Tomorrow' : new Date(d.day + 'T00:00:00Z').toLocaleDateString(undefined, { weekday: 'short', month: 'numeric', day: 'numeric' });
- const full = d.open <= 0;
- return '
';
- }).join('');
- grid.querySelectorAll('.feat-day:not(.full)').forEach(el =>
- el.addEventListener('click', () => { featStartDay = Number(el.dataset.off); featHint(); }));
- }
- const dys = Number($('cFeatDays').value) || (lastRates.featuredDurations[0]);
- const dayLabel = featStartDay === 0 ? 'today' : featStartDay === 1 ? 'tomorrow' : 'in ' + featStartDay + ' days';
- $('cFeatHint').textContent = 'Runs ' + dys + ' day' + (dys > 1 ? 's' : '') + ' starting ' + dayLabel
- + ' for ' + (dys * lastRates.featuredPerDay) + ' credits. Max ' + (s ? s.slotsPerDay : 10) + ' links share any day.';
- }
- document.addEventListener('change', e => { if (e.target && e.target.id === 'cFeatDays') featHint(); });
- function visitHint() {
- if (!lastRates) return;
- const n = Number($('cVisitCount').value) || 0;
- const cost = n * (lastRates.visitCostPerVisit || 3);
- $('cVisitHint').textContent = (lastRates.visitCostPerVisit || 3) + ' credits per verified visit'
- + (n >= (lastRates.visitMinPack || 20) ? ' — ' + n + ' visits = ' + cost + ' credits' : ' (min ' + (lastRates.visitMinPack || 20) + ')')
- + '. Each is a unique member, dwell + human-check verified.';
- }
- $('cVisitCount').addEventListener('input', visitHint);
- // video composer: tier dropdown + upload + price hint
- function videoHint() {
- if (!lastRates || !lastRates.videoTiers) return;
- if ($('cWatchSecs') && !$('cWatchSecs').options.length)
- $('cWatchSecs').innerHTML = lastRates.videoTiers.map(t =>
- '').join('');
- const tier = lastRates.videoTiers.find(t => t.secs === Number($('cWatchSecs').value)) || lastRates.videoTiers[0];
- const n = tier ? Math.floor((Number($('cBudget').value) || 0) / tier.cost) : 0;
- $('cVideoHint').textContent = tier ? (tier.cost + ' credits per completed ' + tier.secs + 's view'
- + (n ? ' — this budget buys ' + n + ' views' : '') + '. Viewers earn ' + tier.reward + ' credits each, so they watch.') : '';
- }
- document.addEventListener('change', e => { if (e.target && e.target.id === 'cWatchSecs') videoHint(); });
- $('cBudget').addEventListener('input', () => { if ($('cType').value === 'video') videoHint(); });
- $('cVideoUploadBtn').addEventListener('click', () => $('cVideoFile').click());
- $('cVideoUrl').addEventListener('change', async () => {
- const url = $('cVideoUrl').value.trim();
- $('cVideoInfo').textContent = url ? 'checking video…' : '';
- cVidDims = url ? await probeVideoDims(url) : null;
- if (url && !cVidDims) $('cVideoInfo').textContent = 'could not read that video';
- else { $('cVideoInfo').textContent = ''; showVidOrient(); }
- });
- $('cVideoFile').addEventListener('change', async () => {
- const f = $('cVideoFile').files[0];
- if (!f) return;
- $('cVideoInfo').textContent = 'Uploading ' + f.name + '… (large files take a moment)';
- try {
- const r = await (await fetch('/api/my/upload', { method: 'POST', headers: { 'Content-Type': f.type }, body: f })).json();
- if (r.error) { $('cVideoInfo').textContent = r.error; $('cVideoFile').value = ''; return; }
- $('cVideoUrl').value = r.url;
- $('cVideoInfo').textContent = f.name + ' uploaded';
- $('cVideoPrev').hidden = false;
- $('cVideoPrev').innerHTML = '';
- cVidDims = await probeVideoDims(r.url); showVidOrient();
- } catch (e) { $('cVideoInfo').textContent = 'Upload failed. Try again.'; }
- $('cVideoFile').value = '';
- });
- $('createCampBtn').addEventListener('click', busy2($('createCampBtn'), async () => {
- // in raw mode the source of truth is the textarea; sync it back first
- let soloBody = $('cSoloEd').innerHTML;
- if ($('cSoloRaw') && !$('cSoloRaw').hidden) soloBody = $('cSoloRaw').value;
- const t = $('cType').value;
- const isVideo = t === 'video', isFeat = t === 'featured';
- if (isVideo && !cVidDims && $('cVideoUrl').value) cVidDims = await probeVideoDims($('cVideoUrl').value);
- await api('/api/my/campaigns', { type: t, name: $('cName').value,
- targetUrl: $('cTarget').value, imageUrl: $('cImage').value, size: $('cSize').value,
- title: isVideo ? $('cVideoTitle').value : isFeat ? $('cFeatTitle').value : t === 'visits' ? $('cVisitTitle').value : $('cTitle').value,
- body: t === 'solo' ? soloBody : $('cBody').value,
- videoUrl: $('cVideoUrl').value, watchSecs: Number($('cWatchSecs').value),
- videoW: cVidDims ? cVidDims.w : null, videoH: cVidDims ? cVidDims.h : null,
- days: Number($('cFeatDays').value), startDay: featStartDay,
- count: Number($('cVisitCount').value),
- dailyCap: ($('cDailyCap') && (t === 'banner' || t === 'text')) ? Number($('cDailyCap').value) || 0 : 0,
- geo: [...document.querySelectorAll('.geoTier:checked')].map(x => x.value).join(','),
- startsAt: ($('cStartAt') && $('cStartAt').value && !isFeat) ? new Date($('cStartAt').value).getTime() : 0,
- endsAt: ($('cEndAt') && $('cEndAt').value && !isFeat) ? new Date($('cEndAt').value).getTime() : 0,
- ctaLabel: isVideo ? $('cVideoCta').value : $('cCtaLabel').value,
- budget: isFeat ? (Number($('cFeatDays').value) * (lastRates.featuredPerDay || 40)) : t === 'visits' ? (Number($('cVisitCount').value) * (lastRates.visitCostPerVisit || 3)) : Number($('cBudget').value) });
- const schedStart = ($('cStartAt') && $('cStartAt').value && !isFeat) ? new Date($('cStartAt').value) : null;
- IAP.status(schedStart && schedStart.getTime() > Date.now() ? 'Campaign saved. It starts serving ' + schedStart.toLocaleString([], { dateStyle: 'medium', timeStyle: 'short' }) + '.' : 'Campaign is live. It starts serving right away.', 'ok');
- // clear EVERY field so no target/creative carries into the next campaign
- ['cName', 'cBudget', 'cTarget', 'cImage', 'cTitle', 'cBody', 'cCtaLabel',
- 'cVideoUrl', 'cVideoTitle', 'cVideoCta', 'cVisitTitle', 'cVisitCount', 'cFeatTitle', 'cDailyCap', 'cStartAt', 'cEndAt']
- .forEach(id => { if ($(id)) $(id).value = ''; });
- document.querySelectorAll('.geoTier').forEach(x => { x.checked = true; });
- $('cSoloEd').innerHTML = ''; if ($('cSoloRaw')) $('cSoloRaw').value = '';
- $('cVideoInfo').textContent = ''; $('cVideoPrev').hidden = true; $('cVideoPrev').innerHTML = '';
- if ($('edMediaInfo')) $('edMediaInfo').textContent = '';
- cVidDims = null;
- await loadCampaigns();
- }));
- // defers the busy() lookup to click time (busy is declared below)
- function busy2(btn, fn) { return (...a) => busy(btn, fn)(...a); }
-
- // ── verified visits: open a member's site (new tab), dwell, human-check, earn ──
- const visState = { token: null, id: null, dwell: 8 };
- async function loadVisitStatus() {
- try {
- const st = await (await fetch('/api/my/visits')).json();
- if (st.error) return;
- $('vsProgress').textContent = 'today: ' + (st.status.count || 0) + ' / ' + st.status.cap + ' verified visits';
- $('vsStartBtn').hidden = st.status.count >= st.status.cap;
- if (st.status.count >= st.status.cap) $('vsBox').innerHTML = 'That\'s today\'s visits. Come back tomorrow.';
- } catch (e) {}
- }
- async function loadVisit() {
- $('vsCheck').hidden = true; $('vsVisit').hidden = true; $('vsHint').textContent = '';
- let r = null;
- try { r = await (await fetch('/api/my/visits')).json(); } catch (e) {}
- if (!r || !r.ad) {
- $('vsBox').innerHTML = '' + (r && r.status && r.status.count >= r.status.cap
- ? 'That\'s today\'s visits. Come back tomorrow.' : 'No verified-visit packs are running right now. Check back soon.') + '';
- return;
- }
- visState.token = r.token; visState.id = r.ad.id; visState.dwell = r.status.dwell || 8;
- $('vsBox').innerHTML = '' + esc(r.ad.title || 'Member site') + ' Open the site and stay ' + visState.dwell + 's.';
- const visit = $('vsVisit');
- visit.href = r.ad.url; visit.hidden = false;
- $('vsStartBtn').textContent = 'Loading…'; $('vsStartBtn').disabled = true;
- // opening the site starts the dwell; then we ask the human-check
- visit.onclick = () => {
- let left = visState.dwell;
- $('vsHint').textContent = 'Counting your visit: ' + left + 's';
- const t = setInterval(async () => {
- left--;
- if (left > 0) { $('vsHint').textContent = 'Counting your visit: ' + left + 's'; return; }
- clearInterval(t);
- $('vsHint').textContent = 'One quick check to count the visit:';
- let c = await (await fetch('/api/my/visitchallenge?token=' + visState.token)).json();
- if (c.early) { await new Promise(r2 => setTimeout(r2, (c.wait || 1) * 1000 + 300)); c = await (await fetch('/api/my/visitchallenge?token=' + visState.token)).json(); }
- if (c.error) { $('vsHint').textContent = c.error; return; }
- renderVisitCheck(c);
- }, 1000);
- };
- $('vsStartBtn').textContent = 'Next visit'; $('vsStartBtn').disabled = false;
- }
- function renderVisitCheck(c) {
- $('vsPrompt').textContent = 'Click the ' + c.prompt + ':';
- const w = $('vsOpts'); w.innerHTML = '';
- c.options.forEach((em, i) => {
- const b = document.createElement('button');
- b.className = 'btn small sec'; b.style.marginRight = '6px'; b.textContent = em;
- b.addEventListener('click', () => answerVisit(i));
- w.appendChild(b);
- });
- $('vsCheck').hidden = false;
- }
- async function answerVisit(i) {
- const r = await (await fetch('/api/my/visitdone', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ token: visState.token, answer: i }) })).json();
- if (r.error) {
- if (r.retry) { const c = await (await fetch('/api/my/visitchallenge?token=' + visState.token)).json(); if (!c.error) return renderVisitCheck(c); }
- $('vsHint').textContent = r.error; $('vsCheck').hidden = true; return;
- }
- $('vsCheck').hidden = true;
- $('vsHint').textContent = '+' + r.credited + ' credits — visit counted. Load the next one.';
- $('vsProgress').textContent = 'today: ' + (r.status.count || 0) + ' / ' + (r.status.cap || 0) + ' verified visits';
- IAP.status('+' + r.credited + ' credits for a verified visit.', 'ok');
- loadDashboard();
- }
- $('vsStartBtn').addEventListener('click', () => loadVisit());
-
- // ── watch-to-earn videos: escape-proof player, server-clock reward ──
- const vidState = { token: null, secs: 0, maxSeen: 0, done: false, credited: false };
- // detected dimensions of the video being created — portrait goes to Shorts, landscape to Watch videos
- let cVidDims = null;
- function probeVideoDims(url) {
- return new Promise(resolve => {
- if (!url) return resolve(null);
- const v = document.createElement('video'); v.preload = 'metadata'; v.muted = true;
- let done = false; const fin = r => { if (!done) { done = true; resolve(r); } };
- v.onloadedmetadata = () => fin(v.videoWidth && v.videoHeight ? { w: v.videoWidth, h: v.videoHeight } : null);
- v.onerror = () => fin(null); setTimeout(() => fin(null), 8000); v.src = url;
- });
- }
- function showVidOrient() {
- const el = $('cVideoInfo'); if (!el) return;
- if (!cVidDims) return;
- const portrait = cVidDims.h > cVidDims.w;
- el.textContent = (el.textContent ? el.textContent + ' · ' : '')
- + (portrait ? 'portrait — shows in the Shorts reel' : 'landscape — shows in the Watch videos tab');
- }
- async function loadVideoStatus() {
- try {
- const st = await (await fetch('/api/my/videos?orientation=landscape')).json();
- if (st.error) return;
- $('vidProgress').textContent = 'today: ' + (st.status.count || 0) + ' / ' + st.status.cap + ' videos watched';
- if (st.status.left <= 0) {
- $('vidBox').innerHTML = 'That is today\'s video set. Come back tomorrow.';
- $('vidStartBtn').hidden = true;
- return;
- }
- $('vidStartBtn').hidden = false;
- } catch (e) {}
- }
- // leaving the player (other sub-tab, other pane, page hidden) stops the clip: nothing plays or earns in the background (Marty, 2026-09-13)
- function stopVideo() {
- const p = $('vidPlayer'); if (!p) return;
- const was = !!vidState.token && !vidState.done;
- try { p.pause(); p.ontimeupdate = null; p.onseeking = null; p.removeAttribute('src'); p.load(); } catch (e) {}
- vidState.token = null; vidState.done = false; vidState.credited = false; vidState.maxSeen = 0;
- if ($('vidWrap')) $('vidWrap').hidden = true;
- if ($('vidBox')) { $('vidBox').hidden = false; if (was) $('vidBox').innerHTML = 'Video stopped when you left the tab. Tap Load a video to start a fresh one.'; }
- if ($('vidStartBtn')) { $('vidStartBtn').disabled = false; $('vidStartBtn').textContent = 'Load a video'; }
- }
- document.addEventListener('visibilitychange', () => { if (document.hidden && vidState.token && !vidState.done) stopVideo(); });
- async function loadVideoAd() {
- let r = null;
- try { r = await (await fetch('/api/my/videos?orientation=landscape')).json(); } catch (e) {}
- if (!r || !r.ad) {
- // same done screen as Watch ads when the day's videos are finished (Marty, 2026-09-13)
- const capHit = !!(r && r.status && r.status.left <= 0), allWatched = !!(r && r.allWatched);
- $('vidBox').innerHTML = (capHit || allWatched)
- ? '
✓Videos done for today' + (capHit ? 'That is today’s video set (' + r.status.count + ' watched). Fresh videos tomorrow.' : 'You have watched every live video for today; each one pays once a day. New ones appear as members launch video campaigns.') + '
'
- : 'No member videos are live right now. Check back when a campaign is running.';
- if ($('vidStartBtn')) $('vidStartBtn').hidden = capHit || allWatched;
- $('vidBox').hidden = false;
- $('vidWrap').hidden = true;
- return;
- }
- const ad = r.ad;
- vidState.token = r.token; vidState.secs = ad.watchSecs; vidState.maxSeen = 0; vidState.done = false; vidState.credited = false;
- $('vidBox').hidden = true;
- $('vidWrap').hidden = false;
- $('vidCta').hidden = true;
- $('vidHint').textContent = ad.title ? 'Now playing: ' + ad.title : '';
- const p = $('vidPlayer');
- p.src = ad.videoUrl;
- p.currentTime = 0;
- // escape-proof: no seeking past what's been watched; track max reached
- p.onseeking = () => { if (p.currentTime > vidState.maxSeen + 0.5) p.currentTime = vidState.maxSeen; };
- p.ontimeupdate = () => {
- if (p.currentTime > vidState.maxSeen) vidState.maxSeen = p.currentTime;
- const left = Math.max(0, Math.ceil(vidState.secs - vidState.maxSeen));
- $('vidTimer').textContent = left > 0 ? 'Watch ' + left + 's more to earn' : 'Watch time met — finishing…';
- if (!vidState.done && vidState.maxSeen >= vidState.secs) { vidState.done = true; completeVideo(ad); }
- };
- $('vidStartBtn').textContent = 'Playing…';
- $('vidStartBtn').disabled = true;
- try { await p.play(); } catch (e) { $('vidStartBtn').disabled = false; $('vidStartBtn').textContent = 'Tap to play'; }
- $('vidCta').href = ad.ctaUrl;
- $('vidCta').textContent = ad.ctaLabel || 'Learn more';
- $('vidCta').hidden = false;
- }
- async function completeVideo(ad) {
- if (vidState.credited) return;
- vidState.credited = true;
- try {
- const r = await (await fetch('/api/my/videowatch', { method: 'POST',
- headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ token: vidState.token }) })).json();
- if (r.error) { IAP.status(r.error, 'bad'); $('vidHint').textContent = r.error + (/no longer open|stale/.test(r.error) ? ' Loading a fresh one.' : ''); if (/no longer open|stale/.test(r.error)) setTimeout(() => loadVideoAd(), 1200); }
- else if (r.credited) { IAP.status('+' + r.credited + ' credits earned for watching.', 'ok'); $('vidHint').textContent = '+' + r.credited + ' credits earned. Load the next one.'; loadDashboard(); }
- else $('vidHint').textContent = 'That video just ran out of budget — load another.';
- if (r.status) $('vidProgress').textContent = 'today: ' + (r.status.count || 0) + ' / ' + r.status.cap + ' videos watched';
- } catch (e) { IAP.status('Could not confirm that watch. Try the next one.', 'bad'); }
- $('vidStartBtn').disabled = false;
- $('vidStartBtn').textContent = 'Next video';
- }
- $('vidStartBtn').addEventListener('click', () => loadVideoAd());
- // presence enforcement: pause the watch-to-earn video when the tab/window loses focus,
- // resume when it comes back — the viewer must stay on the page for the watch to complete
- document.addEventListener('visibilitychange', () => {
- const p = $('vidPlayer'); if (!p || !p.src) return;
- if (document.hidden) p.pause(); else if (!vidState.done) p.play().catch(() => {});
- });
- window.addEventListener('blur', () => { const p = $('vidPlayer'); if (p && p.src) p.pause(); });
- window.addEventListener('focus', () => { const p = $('vidPlayer'); if (p && p.src && !vidState.done) p.play().catch(() => {}); });
-
- // ── unmissable sponsor-message modal on sign-in ──
- function showSponsorModal(msg) {
- if (!$('msgModal')) return;
- $('mmFrom').textContent = 'A message from ' + (msg.fromName || 'your sponsor');
- $('mmSubject').textContent = msg.subject || '';
- $('mmBody').innerHTML = msg.body || ''; // server-sanitized
- $('msgModal').hidden = false;
- $('mmAck').onclick = async () => {
- $('msgModal').hidden = true;
- try { await fetch('/api/my/messages/' + msg.id + '/read', { method: 'POST' }); } catch (e) {}
- };
- }
-
- // ── coaching: every direct's rung, stalled flag, one-click nudge ──
- // ── pay it forward: send POL from the sponsor's own wallet to a downline's linked address ──
- async function pif(email, name, address) {
- let suggest = 25;
- try { const { products } = await (await fetch('/api/catalog')).json(); const p25 = (products || []).find(p => p.priceCents === 2500); if (p25 && p25.costWei) suggest = Math.ceil(Number(p25.costWei) / 1e18) + 3; } catch (e) {}
- const amt = await IAP.ask({ title: 'Pay it forward', text: 'Send POL from your wallet to ' + name + ' (' + address.slice(0, 6) + '…' + address.slice(-4) + ') for their first package.\nSuggested: the $25 package plus fees. Amount in POL:', type: 'number', value: String(suggest), ok: 'Send POL' });
- if (amt === null) return;
- const pol = Number(amt); if (!(pol > 0)) { IAP.status('Enter an amount in POL.', 'bad'); return; }
- try {
- IAP.status('Confirm the transfer in your wallet…', 'ok');
- const wei = (BigInt(Math.round(pol * 1e6)) * 10n ** 12n).toString();
- const hash = await IAPWallet.sendPol(address, wei);
- await api('/api/my/gift', { email, tx: hash, pol });
- IAP.status('Sent ' + pol + ' POL to ' + name + '. They have been told, with the proof link.', 'ok');
- playSound && playSound('chaching');
- } catch (e) { IAP.status('Transfer not sent: ' + ((e && e.message) || e), 'bad'); }
- }
- // ── holding tank: waiting members, adopt, my open adoptions ──
- const ago = ts => { if (!ts) return 'never'; const d = Math.floor((Date.now() - ts) / 86400000); return d === 0 ? 'today' : d === 1 ? 'yesterday' : d + ' days ago'; };
- async function loadTank() {
- const el = $('tankList'); if (!el) return;
- try {
- const r = await (await fetch('/api/my/tank')).json();
- if (r.error) { el.innerHTML = ''; return; }
- $('tankCap').textContent = r.cap; $('tankTtl').textContent = r.ttlDays;
- $('tankSub').textContent = r.waiting.length ? r.waiting.length + ' waiting' : 'nobody waiting right now';
- const why = $('tankWhy'); why.hidden = r.eligible; why.innerHTML = r.eligible ? '' : 'not yet ' + esc(r.reason);
- $('tankMine').innerHTML = r.mine.length ? '
').join('');
- el.querySelectorAll('[data-adopt]').forEach(b => b.addEventListener('click', async () => {
- const note = await IAP.ask({ title: 'Adopt ' + b.dataset.aname, text: 'Your first message to ' + b.dataset.aname + ' (sent as a chat and an email):', type: 'textarea', ok: 'Adopt and send', value: 'Hi, I picked you up from the LinkSpin holding tank so you have a sponsor who will actually help. Reply here and I will walk you through the first three steps.' });
- if (note === null) return;
- try { const rr = await api('/api/my/tank/adopt', { who: b.dataset.adopt, note }); IAP.status('You are now the sponsor for ' + rr.name + '. Chat and email sent.', 'ok'); loadTank(); loadCoach(); }
- catch (e) { IAP.status(e.message, 'bad'); }
- }));
- } catch (e) {}
- }
- async function loadCoach() {
- loadTank();
- try {
- const r = await (await fetch('/api/my/coach')).json();
- const el = $('coachList'); if (!el || r.error) return;
- const d = r.directs || [];
- $('coachSummary').innerHTML = d.length ? '' + d.length + ' direct' + (d.length === 1 ? '' : 's') + ' · ' + r.stalled + ' quiet for 3+ days' + (r.stalled ? ' · start at the top' : '') : '';
- if (!d.length) { el.innerHTML = '
No directs yet. When someone joins through your link they show up here with their next step.
';
- }
- async function loadPipeline() {
- try {
- const r = await (await fetch('/api/my/pipeline')).json();
- if (r.error) { IAP.status(r.error, 'bad'); return; }
- if (!r.live) {
- $('pipeSoon').hidden = false; $('pipeLive').hidden = true;
- $('pipeSoonEta').textContent = r.eta ? 'Opens ' + r.eta + '. It is on the roadmap so you can see what is coming and when.' : 'It is on the roadmap so you can see what is coming and when.';
- return;
- }
- PIPE = r; $('pipeSoon').hidden = true; $('pipeLive').hidden = false;
- const badge = $('pipeBadge'); if (badge) { const n = r.counts.due + r.counts.stalled; badge.hidden = !n; badge.textContent = n > 9 ? '9+' : n; }
- $('pipeDueCount').hidden = !r.due.length; $('pipeDueCount').textContent = r.due.length;
- $('pipeDue').innerHTML = r.due.length ? '
Nothing due. Set a follow-up date on any card and it shows up here.
';
- $('pipeSummary').textContent = r.counts.total ? r.counts.total + ' people on your board' + (r.counts.stalled ? ', ' + r.counts.stalled + ' stalled' : '') + '. Cards move on their own when something happens on the ledger; open one to add a note, a follow-up date or a tag.' : 'Nobody on your board yet. Add prospects on My line, and everyone who joins through your link appears here on their own.';
- $('pipeBoard').innerHTML = r.columns.map(col => '
Glad you are in. Three things today, in this order:
Pick your username on the Profile tab (it becomes your link).
Wallet tab: Connect and link wallet, then Switch on payouts. Both are free.
Copy your invite link from My line and send it to one person.
Reply here if you get stuck on any of them. That is what I am here for.
' },
- { label: 'Switch on payouts', subject: 'One free step so nothing passes you by', html: '
Quick reminder: if payouts are not switched on yet, do it now on the Wallet tab. One free transaction.
The contract locks each buyer to their sponsor at their first purchase, and payouts only route to wallets that are switched on. Ready early and you never miss one.
' },
- { label: 'The $10 test', subject: 'See a payout land in real time', html: '
Want to see the whole thing work? Buy the $10 package on Buy packages and watch the live ledger while you do it. You will see your credits mint and the split go out in the same transaction.
When you are ready to count as a qualifying buyer for me, the $20 Activation package is the one.
' },
- { label: 'Qualified Start', subject: 'How to open level 2 today with your own positions', html: '
You can be your own first buyers, openly. On Buy packages, the Qualified Start card lets you link a second wallet you own as a position. When it buys a $25 package, it counts as a qualifying buyer, half comes straight back to your main wallet, and the credits pool with yours.
Two positions open level 2 the same day. The three Qualified Start videos in Training show every click.
' },
- { label: 'Share your link', subject: 'One conversation a day is the whole job', html: '
Promo tools has posts, texts and emails that already carry your link. Pick one and send it to one person today.
Do not wait for the perfect moment. Nobody who waited ever built a line.
' }
- ];
- (function () {
- const w = $('bcTemplates'); if (!w) return;
- w.innerHTML = BC_TEMPLATES.map((t, i) => '').join('');
- w.querySelectorAll('[data-bct]').forEach(b => b.addEventListener('click', () => { const t = BC_TEMPLATES[Number(b.dataset.bct)]; $('bcSubject').value = t.subject; $('bcEd').innerHTML = t.html; $('bcEd').focus(); }));
- })();
- // ── Qualified Start calculator ──
- (function () {
- const n = $('qcN'), pk = $('qcPkg'), out = $('qcOut'); if (!n || !pk || !out) return;
- const CR = { 25: 2500, 50: 5000, 100: 10000, 250: 25000, 500: 50000 }; // flat credits = cents (Marty 2026-10-07)
- const calc = () => {
- const k = Math.max(1, Math.min(10, Number(n.value) || 1)), usd = Number(pk.value) || 25;
- const gross = k * usd, back = gross / 2, net = gross - back, credits = k * (CR[usd] || 0);
- const level = k >= 5 ? 'Level 3 open (and level 2): the Nexus badge, wall position 3, full 50 / 20 / 10' : k >= 2 ? 'Level 2 open: 20% on your directs\' buyers, wall position 2' : 'Counts as one qualifying buyer. One more opens level 2.';
- out.innerHTML = '
$' + gross + ' out across ' + k + ' position' + (k === 1 ? '' : 's') + ' $' + back + ' back to your main wallet in the same transactions (the 50% direct-sponsor share) $' + net + ' net, plus a little POL for gas in each wallet
'
- + '
' + credits.toLocaleString() + ' credits pooled for your own ads ' + level + ' The 20% and 10% shares go to your upline if they are qualified, otherwise to the platform.
').join('');
- // opening the pane marks them read
- for (const i of r.items) if (!i.read) fetch('/api/my/messages/' + i.id + '/read', { method: 'POST' }).catch(() => {});
- } catch (e) {}
- }
- // broadcast composer editor (its own small rich editor, server sanitizes)
- document.querySelectorAll('[data-bc]').forEach(b =>
- b.addEventListener('click', () => { $('bcEd').focus(); document.execCommand(b.dataset.bc, false, null); }));
- document.querySelectorAll('[data-bcblock]').forEach(b =>
- b.addEventListener('click', () => { $('bcEd').focus(); document.execCommand('formatBlock', false, b.dataset.bcblock); }));
- if ($('bcLinkBtn')) $('bcLinkBtn').addEventListener('click', async () => {
- const sel = window.getSelection(); const range = sel && sel.rangeCount ? sel.getRangeAt(0).cloneRange() : null;
- const u = await IAP.ask({ title: 'Insert link', text: 'Link URL (https://…)', placeholder: 'https://', ok: 'Insert' });
- if (u) { $('bcEd').focus(); if (range) { sel.removeAllRanges(); sel.addRange(range); } document.execCommand('createLink', false, u); }
- });
- if ($('bcSendBtn')) $('bcSendBtn').addEventListener('click', busy2($('bcSendBtn'), async () => {
- const r = await api('/api/my/broadcast', { scope: $('bcScope').value, subject: $('bcSubject').value, body: $('bcEd').innerHTML });
- IAP.status('Broadcast sent to ' + r.sent + ' member' + (r.sent === 1 ? '' : 's') + '.', 'ok');
- $('bcSubject').value = ''; $('bcEd').innerHTML = '';
- $('bcHint').textContent = 'Sent. You can send your next broadcast in 24 hours.';
- }));
-
- // ── solo-ads inbox: list, read view, dwell-gated read reward ──
- let ibTimer = null;
- function setInboxBadge(n) {
- for (const id of ['inboxBadge', 'inboxBadge2']) {
- const b = $(id);
- if (b) { b.hidden = !n; b.textContent = n; }
- }
- }
- // Earn credits sub-tabs: Watch ads | Inbox
- let earnSub = 'watch';
- function setEarnSub(which) {
- earnSub = ['inbox', 'videos', 'visits'].includes(which) ? which : 'watch';
- if (earnSub !== 'videos' && vidState.token) stopVideo();
- const w = $('earn-watch'), i = $('earn-inbox'), v = $('earn-videos'), vs = $('earn-visits');
- if (w) w.hidden = earnSub !== 'watch';
- if (i) i.hidden = earnSub !== 'inbox';
- if (v) v.hidden = earnSub !== 'videos';
- if (vs) vs.hidden = earnSub !== 'visits';
- document.querySelectorAll('.subtabs [data-earn]').forEach(b =>
- b.classList.toggle('on', b.dataset.earn === earnSub));
- if (earnSub === 'inbox') loadInbox();
- else if (earnSub === 'videos') loadVideoStatus();
- else if (earnSub === 'visits') loadVisitStatus();
- else earnRefresh();
- }
- document.querySelectorAll('.subtabs [data-earn]').forEach(b =>
- b.addEventListener('click', () => setEarnSub(b.dataset.earn)));
- // promo toolkit: badge tiers + the AI Copy Engine (Marty, 2026-09-14)
- let tkState = null;
- async function loadToolkit() {
- try {
- const r = await (await fetch('/api/my/toolkit')).json(); if (r.error) return; tkState = r;
- const esc = t => String(t == null ? '' : t).replace(/[&<>"]/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"' }[c]));
- const names = { free: 'Free', spark: 'Spark', surge: 'Surge', circuit: 'Circuit', nexus: 'Nexus' };
- $('tkTierLine').textContent = 'you are at ' + names[r.tier];
- $('tkTiers').innerHTML = r.tiers.map(t => '
' + esc(t.name) + (t.reached ? ' ✓' : '') + '
' + (t.reached ? esc(t.blurb) : 'Unlocks when you ' + esc(t.needText)) + '
' + t.items.map(i => '
' + esc(i.t) + '
').join('') + '
' + (t.reached ? '' : '
locked
') + '
').join('');
- $('tkLocked').hidden = r.unlocked; $('tkForm').hidden = !r.unlocked;
- if (!r.unlocked) { $('tkLocked').textContent = 'Unlocks at Surge: your first qualifying buyer of a $25 or larger package. Then it writes posts, DMs, follow-ups, objection replies, emails and story posts in your name, with your link, inside the honesty rules. ' + (r.tier === 'free' ? 'Step one is switching on payouts.' : 'You are one buyer away.'); $('tkUsage').textContent = 'locked'; renderTkTools(r); return; }
- $('tkUsage').textContent = r.freeLeft + ' free this month · then ' + r.cost + ' credits each · you have ' + r.available.toLocaleString() + ' credits';
- $('tkCostLine').textContent = r.freeLeft > 0 ? 'This one is free (' + r.freeLeft + ' left this month).' : 'This one costs ' + r.cost + ' credits from your earned pool.';
- if (!$('tkKind').options.length) { $('tkKind').innerHTML = r.kinds.map(k => '').join(''); $('tkAngle').innerHTML = r.angles.map(a => '').join(''); }
- renderTkTools(r);
- $('tkHistory').innerHTML = r.history.length ? '
').join('') : '';
- } catch (e) { console.error('toolkit', e); }
- }
- // the rest of the ladder: Spark templates + handout, Circuit Video Maker + split tester, Nexus Leader Ops
- const tkEsc = t => String(t == null ? '' : t).replace(/[&<>"]/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"' }[c]));
- const tkRank = { free: 0, spark: 1, surge: 2, circuit: 3, nexus: 4 };
- async function tkPost(url, body) { const r = await (await fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body || {}) })).json(); if (r.error) { IAP.status(r.error, 'bad'); return null; } return r; }
- function renderTkTools(r) {
- const at = tkRank[r.tier] || 0;
- // Spark
- const spark = at >= 1; $('tkSparkLocked').hidden = spark; $('tkSparkBody').hidden = !spark;
- if (!spark) $('tkSparkLocked').textContent = 'Unlocks at Spark: switch on payouts in the Wallet tab. Then one tap builds a banner or text campaign aimed at your link, and you get a printable handout with your QR.';
- else { $('tkHandoutLine').hidden = !r.handoutUrl; if (r.handoutUrl) $('tkHandout').href = r.handoutUrl; }
- // Circuit
- const circ = at >= 3; $('tkCircuitLocked').hidden = circ; $('tkCircuitBody').hidden = !circ;
- if (!circ) $('tkCircuitLocked').textContent = 'Unlocks at Circuit: two qualifying buyers in your line. Then every promo video gets your own end card and QR, and the split tester shows which join angle pulls for you.';
- else { loadTkVideos(r); loadTkSplit(); }
- // Nexus
- const nex = at >= 4; $('tkNexusLocked').hidden = nex; $('tkNexusBody').hidden = !nex;
- if (!nex) $('tkNexusLocked').textContent = 'Unlocks at Nexus: five qualifying buyers. Then you get team triage across three levels with one-click nudges, AI-drafted team broadcasts, credit grants to your people, a co-branded join page and your own partner code.';
- else { loadTkTeam(); renderTkPartner(r); }
- }
- let tkVidTimer = null;
- async function loadTkVideos(r) {
- const box = $('tkVideos');
- if (!r.videoMaker) { box.innerHTML = '
The Video Maker is warming up on the server. Check back shortly.
'; return; }
- if (!r.username) { box.innerHTML = '
Pick a username first (Profile); it goes on the end card.
Code ' + tkEsc(pk.code) + ' gives ' + pk.credits + ' welcome credits, funded from your earned pool at each redemption. Redeemed ' + pk.uses + ' times.
Invite link with the code: ' + tkEsc(pk.link) + '
Your partner kit page (for list owners and site owners you talk to): ' + tkEsc(pk.kit) + '
'
- : '
Give your recruits a welcome bonus under your own code. Each redemption moves the credits from your earned pool to theirs, so it only costs you when it works. Then hand partners the kit page, which sends their deals under you.
';
- }
- document.addEventListener('click', async ev => {
- const b = ev.target.closest('[data-tpl],[data-mkvid],[data-copyvid],[data-nudge],[data-copy],#tkPcGo,#tkGrantGo,#tkDraftBc,[data-sendnudge]'); if (!b) return;
- if (b.dataset.tpl) { b.disabled = true; const r = await tkPost('/api/my/toolkit/template', { kind: b.dataset.tpl, budget: Number($('tkTplBudget').value) }); b.disabled = false; if (r) { IAP.status('Campaign "' + r.name + '" created with ' + r.budget + ' credits. It is under Campaigns.', 'ok'); loadDashboard(); } return; }
- if (b.dataset.mkvid) { b.disabled = true; const r = await tkPost('/api/my/toolkit/video', { slug: b.dataset.mkvid }); if (r) { IAP.status(r.status === 'done' ? 'Already made.' : 'Rendering. It appears here in about a minute.', 'ok'); loadTkVideos(tkState); } else b.disabled = false; return; }
- if (b.dataset.copyvid || b.dataset.copy) { try { await navigator.clipboard.writeText(b.dataset.copyvid || b.dataset.copy); IAP.status('Copied.', 'ok'); } catch (e) { IAP.status('Copy failed; select it by hand.', 'bad'); } return; }
- if (b.dataset.nudge) { const row = b.closest('.tk-team'); const old = row.querySelector('.tk-nudge'); if (old) { old.remove(); return; } const box = document.createElement('div'); box.className = 'tk-nudge'; box.innerHTML = '
Lands in their inbox and their email.
'; box.querySelector('textarea').value = b.dataset.say; row.appendChild(box); return; }
- if (b.dataset.sendnudge) { const box = b.closest('.tk-nudge'); b.disabled = true; const r = await tkPost('/api/my/toolkit/nudge', { email: b.dataset.sendnudge, text: box.querySelector('textarea').value }); b.disabled = false; if (r) { IAP.status('Sent.', 'ok'); box.remove(); } return; }
- if (b.id === 'tkGrantGo') { b.disabled = true; const r = await tkPost('/api/my/toolkit/grant', { email: $('tkGrantTo').value, credits: Number($('tkGrantN').value) }); b.disabled = false; if (r) { IAP.status(r.credits + ' credits moved to ' + r.toName + '.', 'ok'); loadToolkit(); loadDashboard(); } return; }
- if (b.id === 'tkPcGo') { b.disabled = true; const r = await tkPost('/api/my/toolkit/promo', { code: b.dataset.code || ($('tkPcCode') ? $('tkPcCode').value : ''), credits: Number($('tkPcN').value) }); b.disabled = false; if (r) { IAP.status('Code ' + r.code + ' is live: ' + r.credits + ' welcome credits.', 'ok'); loadToolkit(); } return; }
- if (b.id === 'tkDraftBc') { if (!tkState || !tkState.unlocked) return; $('tkKind').value = 'broadcast'; $('tkBrief').placeholder = 'What should the team focus on this week?'; $('tkEngine').scrollIntoView({ behavior: 'smooth', block: 'start' }); $('tkBrief').focus(); IAP.status('Pick a focus, hit Write it, then Send to my team.', 'ok'); return; }
- });
- $('tkKind') && $('tkKind').addEventListener('change', () => { if ($('tkSendBc')) $('tkSendBc').hidden = $('tkKind').value !== 'broadcast'; });
- async function tkSendBroadcast() {
- const txt = $('tkText').value || ''; const m = /^\s*Subject:\s*(.+)\n+([\s\S]+)$/.exec(txt);
- const subject = m ? m[1].trim() : 'A note from your sponsor', body = (m ? m[2] : txt).trim();
- if (!(await IAP.confirmBox('Send this to everyone in your three levels? One broadcast a day.', { title: 'Team broadcast', ok: 'Send' }))) return;
- const r = await tkPost('/api/my/broadcast', { subject, body: '
Pooled credits: ' + (r.totalCredits || 0).toLocaleString() + '' + (r.credited ? ' plus ' + r.credited.toLocaleString() + ' credited to your account (spends from any position)' : '') + '. A campaign budget spends from one position at a time.
' : '');
- if ($('qsList')) $('qsList').innerHTML = html;
- // Wallet tab: live POL balance of the linked wallet, and which package it covers
- const wb = $('walletBal');
- if (wb && r.main && r.main.address && r.main.balanceWei != null) {
- const polN = Number(BigInt(r.main.balanceWei) / 10n ** 14n) / 10000;
- const usd = r.polUsd ? polN * r.polUsd : 0;
- const pkgs = [5, 20, 50, 100, 250];
- const covers = r.polUsd ? pkgs.filter(p => usd >= p * 1.06 + 0.05) : [];
- wb.hidden = false;
- wb.innerHTML = 'Wallet balance: ' + polN.toLocaleString(undefined, { maximumFractionDigits: 2 }) + ' POL' + (usd ? ' (about $' + usd.toLocaleString(undefined, { maximumFractionDigits: 0 }) + ')' : '')
- + (r.polUsd ? ' ' + (covers.length ? 'Enough for the $' + covers[covers.length - 1] + ' package with gas to spare.' : 'Not enough for the $5 package yet. Buy POL with a card on the Buy packages tab, or send POL to this wallet.') + (covers.length && covers.length < pkgs.length ? ' Top up for the $' + pkgs[covers.length] + ' package.' : '') + '' : '');
- }
- if ($('posList')) $('posList').innerHTML = html;
- if ($('posCard')) $('posCard').hidden = !list.length;
- // "Buy from" picker: main + every position
- const sel = $('buyFrom');
- if (sel) {
- const keep = sel.value;
- sel.innerHTML = ''
- + list.map((p, i) => '').join('');
- noPayoutAddrs = new Set(list.filter(p => p.noPayout).map(p => p.address.toLowerCase())); if (r.main && r.main.noPayout && r.main.address) noPayoutAddrs.add(r.main.address.toLowerCase());
- if (keep && [...sel.options].some(o => o.value === keep)) sel.value = keep;
- $('buyFromWrap').hidden = !list.length;
- }
- document.querySelectorAll('[data-unlink]').forEach(b => b.addEventListener('click', async () => {
- if (!(await IAP.confirmBox('Unlink ' + short(b.dataset.unlink) + ' from your account?', { title: 'Unlink position', ok: 'Unlink' }))) return;
- try { await api('/api/my/positions/remove', { address: b.dataset.unlink }); IAP.status('Position unlinked.', 'ok'); loadPositions(); }
- catch (e) { IAP.status(e.message, 'bad'); }
- }));
- } catch (e) {}
- }
- if ($('qsAddBtn')) $('qsAddBtn').addEventListener('click', busy2($('qsAddBtn'), async () => {
- const me = await (await fetch('/api/me')).json();
- if (!me.address) throw new Error('Link your main wallet first (Wallet tab), then add positions under it.');
- if (!me.memberId) throw new Error('Switch on payouts for your main wallet first (Wallet tab). Positions register under your member number.');
- if (!(await IAP.confirmBox('Your wallet will ask which account to connect. Tick ONLY the new account (not ' + short(me.address) + '), then sign once.\n\nIf you have not created the extra account yet: MetaMask, account menu, Add account. Trust or SafePal: switch wallet.\n\nReady?', { title: 'Add a position', ok: 'Ready' }))) return;
- IAP.status('Pick the new account in your wallet, then sign once…');
- const r = await IAPWallet.signIn({ asPosition: true, pick: true });
- $('qsHint').textContent = 'Added ' + short(r.address) + '. Now choose it under "Buy from" and buy a $25 or larger package.';
- IAP.status('Position added: ' + short(r.address) + '. Pick it under "Buy from" above and buy a $25+ package to count it.', 'ok');
- await loadPositions();
- const sel = $('buyFrom'); if (sel) sel.value = r.address.toLowerCase();
- try { $('buyFrom').scrollIntoView({ behavior: 'smooth', block: 'center' }); } catch (e) {}
- }));
- async function loadBuyTiles() {
- try {
- const { products } = await (await fetch('/api/catalog')).json();
- const wrap = $('boTiles');
- wrap.innerHTML = '';
- for (const p of products) {
- const bonus = p.creditAmount - p.priceCents;
- const div = document.createElement('div');
- div.className = 'tile' + (p.priceCents === 5000 ? ' hot' : '');
- div.innerHTML = '
' + (p.costWei ? IAP.fmtPol(p.costWei) + ' POL right now' : 'paused') + '
'
- + '';
- wrap.appendChild(div);
- }
- wrap.querySelectorAll('button[data-id]').forEach(b => b.addEventListener('click', async () => {
- try {
- b.disabled = true;
- // the buyer's credits are read by the member id of their LINKED wallet.
- // If they only connected a wallet (e.g. for the faucet) but never linked
- // it, link it first (one signature) so the purchase's credits show up.
- // retry these through transient failures — mobile drops in-flight
- // fetches when the page returns from the wallet app-switch
- const jretry = async url => { let err; for (let i = 0; i < 4; i++) { try { return await (await fetch(url)).json(); } catch (e) { err = e; await new Promise(s => setTimeout(s, 500 * (i + 1))); } } throw err; };
- const meNow = await jretry('/api/me');
- // which of the member's wallets is buying: the main wallet (default) or a
- // linked position (Qualified Start). A position registers under the main
- // member id on its first buy, so its sponsor is always this member.
- const fromSel = $('buyFrom');
- const fromPos = (fromSel && !$('buyFromWrap').hidden && fromSel.value && fromSel.value !== 'main') ? fromSel.value.toLowerCase() : null;
- if (fromPos && !meNow.memberId) { IAP.status('Switch on payouts for your main wallet first (Wallet tab), so this position can register under you.', 'bad'); return; }
- if (noPayoutAddrs.has(fromPos || String(meNow.address || '').toLowerCase())) { IAP.status('This position is kept for linkage only. A purchase from it would pay a retired wallet. Buy from your main wallet or another position.', 'bad'); return; }
- if (!fromPos && !meNow.address) {
- IAP.status('Link your wallet first — one quick signature…');
- await IAPWallet.signIn();
- }
- const wantAddr = fromPos || (meNow.address ? meNow.address.toLowerCase() : null);
- if (wantAddr) { // never buy from a wallet other than the one selected: a stray wallet would register a brand-new member
- await IAPWallet.connect();
- let cur = String(await IAPWallet.activeAddress() || '').toLowerCase();
- if (cur !== wantAddr) {
- IAP.status('Pick ' + wantAddr.slice(0, 6) + '…' + wantAddr.slice(-4) + ' in your wallet\'s account picker…');
- cur = String(await IAPWallet.pickAccount() || '').toLowerCase();
- }
- if (cur !== wantAddr) throw new Error('Your wallet connected as ' + cur.slice(0, 6) + '…' + cur.slice(-4) + ' but you chose ' + wantAddr.slice(0, 6) + '…' + wantAddr.slice(-4) + '. Switch accounts in your wallet app and try again.');
- }
- const spNow = fromPos ? { sponsorId: meNow.memberId } : await jretry('/api/sponsor?intent=buy');
- if (!fromPos && !meNow.memberId && spNow.sponsorBlocked) { IAP.status(sponsorHoldText(spNow), 'bad'); return; } // first activation must not hand a sponsored member to the company
- // pre-flight: stop early if the POL is not there. Trust Wallet also hard-blocks any
- // transaction that spends most of the balance ("drain your wallet"), so Trust users
- // get a heads-up first; other wallets go straight to the confirmation.
- try {
- const need = BigInt(b.dataset.cost) + BigInt(b.dataset.cost) / 50n; // same 2% pad as buy()
- const bal = await IAPWallet.balance(wantAddr || IAPWallet.address() || meNow.address);
- if (bal < need) {
- IAP.status('That wallet holds ' + IAP.fmtPol(bal.toString()) + ' POL, but this package needs about ' + IAP.fmtPol(need.toString()) + ' POL plus a little for gas. Top it up and try again.', 'bad');
- return;
- }
- const pct = Number(need * 100n / bal);
- const isTrust = /trust/i.test(IAPWallet.walletName() || '');
- if (isTrust && pct > 55 && !(await IAP.confirmBox('Heads up for Trust Wallet users: this purchase uses about ' + pct + '% of the POL in your wallet, and Trust Wallet refuses transactions that spend most of the balance (it shows a "drain your wallet" warning with only Stop and go back).' + '\n\n' + 'Options: pick a smaller package first, add some POL, or connect a different wallet (MetaMask, Phantom, SafePal). Extra POL always stays yours.' + '\n\n' + 'Try it anyway?', { title: 'Trust Wallet check', ok: 'Buy anyway', cancel: 'Pause' }))) {
- IAP.status('Purchase paused. Pick a smaller package, add POL, or connect another wallet, then try again.', 'ok');
- return;
- }
- } catch (e) { /* balance read failed: let the wallet decide */ }
- IAP.status('Confirm the purchase in your wallet…');
- const r = await IAPWallet.buy(Number(b.dataset.id), spNow.sponsorId || 0, b.dataset.cost);
- if (r.status !== '0x1' && r.receipt && r.receipt.status !== '0x1') throw new Error('Transaction reverted.');
- IAP.status(fromPos ? 'Purchase settled on-chain. That position now counts toward your qualification, and its credits pool with yours.' : 'Purchase settled on-chain. Credits are in your account.', 'ok');
- await render();
- loadBuyTiles();
- } catch (e) { IAP.status('Purchase failed: ' + ((e && e.message) || e), 'bad'); }
- finally { b.disabled = false; }
- }));
- // brand new to crypto? point to the wallet guide (buy POL on any exchange or on-ramp, send it to your own wallet)
- const cta = document.createElement('div');
- cta.style.cssText = 'grid-column:1/-1;margin-top:10px;text-align:center';
- cta.innerHTML = '
New to crypto? Buy POL with a card on any major exchange or on-ramp, then send it to your own wallet on the Polygon network. This site never touches your money.
'
- + 'Wallet help';
- wrap.appendChild(cta);
- } catch (e) {}
- }
- loadBuyTiles();
-
- // ── earn-by-viewing: daily ad set with dwell, then claim ──
- const earnState = { types: ['banner', 'text'], i: 0, timer: null };
- async function earnRefresh() {
- try {
- const st = await (await fetch('/api/my/earn')).json();
- if (st.error) return null;
- $('earnProgress').textContent = 'today: ' + st.views + ' / ' + st.target + ' ads viewed';
- $('earnBalance').textContent = (st.earnedAvailable != null ? st.earnedAvailable : st.earned) + ' earned credits available' + (st.reserved ? ' · ' + st.reserved + ' in live campaigns' : '');
- const done = st.views >= st.target;
- $('earnClaimBtn').hidden = !(done && !st.claimed);
- if (st.claimed) {
- $('earnHint').textContent = 'Claimed for today' + (st.streakDay > 1 ? ' (streak day ' + st.streakDay + ')' : '') + '. Tomorrow\'s claim pays ' + st.nextClaim + ' credits if you come back.';
- // after the set (Marty, 2026-09-12): keep going with verified visits, and turn the credits into a campaign
- const box = $('earnAdBox');
- if (box) box.innerHTML = '
✓Ads done for todayToday\'s set is viewed and claimed. Fresh ads tomorrow.'
- + '
';
+ el.appendChild(tbl);
+ el.querySelectorAll('button[data-camp]').forEach(b => b.addEventListener('click', async () => {
+ try { await api('/api/my/campaigns/' + b.dataset.camp + '/' + b.dataset.act); await loadCampaigns(); }
+ catch (e) { IAP.status(e.message, 'bad'); }
+ }));
+ el.querySelectorAll('button[data-topup]').forEach(b => b.addEventListener('click', async () => {
+ const n = await IAP.ask({ title: 'Add credits', text: 'How many credits to add to this campaign? More credits buy more views.', type: 'number', placeholder: 'e.g. 100', ok: 'Add credits' });
+ if (!n) return;
+ try { const r = await api('/api/my/campaigns/' + b.dataset.topup + '/topup', { credits: Number(n) });
+ IAP.status('Added ' + r.added + ' credits' + (r.reactivated ? ' — campaign is live again.' : '.'), 'ok');
+ await loadCampaigns(); loadDashboard();
+ } catch (e) { IAP.status(e.message, 'bad'); }
+ }));
+ } catch (e) {}
+ }
+ let lastRates = null, lastSlots = null;
+ function soloHint() {
+ if (!lastRates || $('cType').value !== 'solo') return;
+ const cost = lastRates.soloCostPerRecipient || 5;
+ const n = Math.floor((Number($('cBudget').value) || 0) / cost);
+ $('cSoloHint').textContent = cost + ' credits per guaranteed inbox delivery'
+ + (n ? ' — this budget reaches ' + n + ' members' : '')
+ + '. Readers earn ' + (lastRates.soloReadCredits || 2) + ' credits for a real read, so your message gets opened.';
+ }
+ $('cBudget').addEventListener('input', soloHint);
+ // rich solo editor: small toolbar over contenteditable (CSP allows no external editor);
+ // the server whitelist-sanitizes whatever HTML arrives, this is just authoring comfort
+ document.querySelectorAll('.ed-bar [data-cmd]').forEach(btn =>
+ btn.addEventListener('click', () => { $('cSoloEd').focus(); document.execCommand(btn.dataset.cmd, false, null); }));
+ document.querySelectorAll('.ed-bar [data-block]').forEach(btn =>
+ btn.addEventListener('click', () => { $('cSoloEd').focus(); document.execCommand('formatBlock', false, btn.dataset.block); }));
+ $('edLinkBtn').addEventListener('click', async () => {
+ const sel = window.getSelection(); const range = sel && sel.rangeCount ? sel.getRangeAt(0).cloneRange() : null; // the dialog steals the selection
+ const url = await IAP.ask({ title: 'Insert link', text: 'Link URL (https://…)', placeholder: 'https://', ok: 'Insert' });
+ if (!url) return;
+ $('cSoloEd').focus(); if (range) { sel.removeAllRanges(); sel.addRange(range); }
+ document.execCommand('createLink', false, url);
+ });
+ // inline media: upload, then drop the element at the cursor (BV-style)
+ let mediaMode = 'image';
+ function insertHtmlAtCursor(html) {
+ const ed = $('cSoloEd');
+ ed.focus();
+ if (!document.execCommand('insertHTML', false, html)) ed.insertAdjacentHTML('beforeend', html);
+ }
+ $('edImgBtn').addEventListener('click', () => { mediaMode = 'image'; $('cSoloFile').accept = 'image/png,image/jpeg,image/webp,image/gif'; $('cSoloFile').click(); });
+ $('edVidBtn').addEventListener('click', () => { mediaMode = 'video'; $('cSoloFile').accept = 'video/mp4,video/webm'; $('cSoloFile').click(); });
+ $('cSoloFile').addEventListener('change', async () => {
+ const f = $('cSoloFile').files[0];
+ if (!f) return;
+ $('edMediaInfo').textContent = 'Uploading ' + f.name + '…';
+ try {
+ const r = await (await fetch('/api/my/upload', { method: 'POST', headers: { 'Content-Type': f.type }, body: f })).json();
+ if (r.error) { $('edMediaInfo').textContent = r.error; $('cSoloFile').value = ''; return; }
+ insertHtmlAtCursor(r.type === 'video'
+ ? '
'
+ : '
');
+ $('edMediaInfo').textContent = f.name + ' inserted';
+ } catch (e) { $('edMediaInfo').textContent = 'Upload failed. Try again.'; }
+ $('cSoloFile').value = '';
+ });
+ // raw-text toggle: swap the WYSIWYG surface for the underlying HTML and back
+ $('edRawBtn').addEventListener('click', () => {
+ const ed = $('cSoloEd'), raw = $('cSoloRaw');
+ if (raw.hidden) { raw.value = ed.innerHTML; raw.hidden = false; ed.hidden = true; $('edRawBtn').textContent = 'Visual'; }
+ else { ed.innerHTML = raw.value; ed.hidden = false; raw.hidden = true; $('edRawBtn').textContent = 'Raw text'; }
+ });
+ const WHERE = { banner: 'Runs in the ad viewer, on the home page, the live ledger, every Overview, the sidebar tile, and out in the Network Ad Space rotation across the wider network.',
+ text: 'Runs in the ad viewer, the live ledger text slot, and out in the Network Ad Space rotation.',
+ login: 'Full screen for every member who signs in, ten seconds, once a day per member. Opens in a fresh tab, so any working page qualifies. A slot is 1,000 purchased credits for 30 days of unlimited sign-in impressions, never charged per day. 3 slots at a time, first come first served. Login ads spend purchased credits only.',
+ solo: 'Delivered into member inboxes under Earn credits. Each read is timed and rewarded, so it gets opened.',
+ video: 'Plays in Watch videos and the Shorts feed under Earn credits. You pay only for completed watches.',
+ featured: 'Your headline and link in the Featured strip on every member Overview for the days you book.',
+ visits: 'A distinct member opens your site in a new tab, stays eight seconds and passes a check. Nobody counts twice.' };
+ const whereHint = () => { const el = $('cWhere'); if (!el) return; const t = $('cType').value; let s = WHERE[t] || '';
+ if (t === 'login' && lastRates) s = s.replace('1,000', (lastRates.loginSlotCredits || 1000).toLocaleString()).replace('30 days', (lastRates.loginSlotDays || 30) + ' days').replace('3 slots', (lastRates.loginSlotsMax || 3) + ' slots');
+ if (t === 'login' && lastSlots) s += lastSlots.free ? ' ' + lastSlots.free + ' of ' + lastSlots.max + ' slots open right now.' : ' All ' + lastSlots.max + ' slots are taken right now. You can reserve the next one on the Ads screen (' + location.origin + '/ads): pay now, it starts when a slot frees, and a cancel before then refunds in full.';
+ el.textContent = s; };
+ whereHint();
+ // runs on every type change AND once at load, so the default type (banner) shows its size + image rows immediately
+ function applyType() { // hoisted: loadCampaigns may run before this line is reached
+ whereHint();
+ const t = $('cType').value;
+ $('cImageRow').hidden = t !== 'banner'; // only banners carry a creative; login frames its URL
+ $('cSizeRow').hidden = t !== 'banner';
+ $('cTitleRow').hidden = t !== 'text' && t !== 'solo';
+ $('cBodyRow').hidden = t !== 'text';
+ $('cSoloRow').hidden = t !== 'solo';
+ $('cSoloHint').hidden = t !== 'solo';
+ $('cVideoRow').hidden = t !== 'video';
+ $('cFeaturedRow').hidden = t !== 'featured';
+ $('cVisitsRow').hidden = t !== 'visits';
+ if ($('cSchedRow')) { $('cSchedRow').hidden = t === 'featured'; $('cStartLbl').textContent = t === 'solo' ? 'Send from (optional)' : 'Start (optional)';
+ $('cSchedHint').textContent = t === 'solo' ? 'Deliveries to member inboxes begin at the time you pick, so you can land when people are reading. Leave empty to start now.' : 'Leave both empty to start now and run until the budget is spent. Times are your local time. Anything left when a campaign ends goes back to Available.'; }
+ // fixed-cost types derive their spend (featured = day slots, visits = flat pack),
+ // so hide the free-form Budget field for them to avoid confusion
+ $('cBudgetRow').hidden = (t === 'featured' || t === 'visits');
+ if ($('cCapRow')) $('cCapRow').hidden = !(t === 'banner' || t === 'text');
+ // solo ads have a real floor (5cr x 10 deliveries): default to 50 so 10 isn't rejected
+ if (t === 'solo' && (!$('cBudget').value || Number($('cBudget').value) < 50)) $('cBudget').value = (lastRates && lastRates.soloCostPerRecipient ? lastRates.soloCostPerRecipient : 5) * 10;
+ if (t === 'visits') visitHint();
+ if (t === 'login') $('cBudget').value = (lastRates && lastRates.loginSlotCredits) || 1000; // a slot is one flat price
+ $('cTitle').placeholder = t === 'solo' ? 'Subject line (max 80)' : 'Headline (max 60)';
+ soloHint();
+ if (t === 'video') videoHint();
+ if (t === 'featured') featHint();
+ }
+ $('cType').addEventListener('change', applyType);
+ let featStartDay = 0; // selected start-day offset (0 = today)
+ async function featHint() {
+ if (!lastRates || !lastRates.featuredDurations) return;
+ if ($('cFeatDays') && !$('cFeatDays').options.length)
+ $('cFeatDays').innerHTML = lastRates.featuredDurations.map(dys =>
+ '').join('');
+ let s = null;
+ try { s = await (await fetch('/api/featured/stats')).json(); } catch (e) {}
+ if (s && s.occupancy) {
+ const grid = $('cFeatDaysGrid');
+ grid.innerHTML = s.occupancy.map(d => {
+ const label = d.offset === 0 ? 'Today' : d.offset === 1 ? 'Tomorrow' : new Date(d.day + 'T00:00:00Z').toLocaleDateString(undefined, { weekday: 'short', month: 'numeric', day: 'numeric' });
+ const full = d.open <= 0;
+ return '
';
+ }).join('');
+ grid.querySelectorAll('.feat-day:not(.full)').forEach(el =>
+ el.addEventListener('click', () => { featStartDay = Number(el.dataset.off); featHint(); }));
+ }
+ const dys = Number($('cFeatDays').value) || (lastRates.featuredDurations[0]);
+ const dayLabel = featStartDay === 0 ? 'today' : featStartDay === 1 ? 'tomorrow' : 'in ' + featStartDay + ' days';
+ $('cFeatHint').textContent = 'Runs ' + dys + ' day' + (dys > 1 ? 's' : '') + ' starting ' + dayLabel
+ + ' for ' + (dys * lastRates.featuredPerDay) + ' credits. Max ' + (s ? s.slotsPerDay : 10) + ' links share any day.';
+ }
+ document.addEventListener('change', e => { if (e.target && e.target.id === 'cFeatDays') featHint(); });
+ function visitHint() {
+ if (!lastRates) return;
+ const n = Number($('cVisitCount').value) || 0;
+ const cost = n * (lastRates.visitCostPerVisit || 3);
+ $('cVisitHint').textContent = (lastRates.visitCostPerVisit || 3) + ' credits per verified visit'
+ + (n >= (lastRates.visitMinPack || 20) ? ' — ' + n + ' visits = ' + cost + ' credits' : ' (min ' + (lastRates.visitMinPack || 20) + ')')
+ + '. Each is a unique member, dwell + human-check verified.';
+ }
+ $('cVisitCount').addEventListener('input', visitHint);
+ // video composer: tier dropdown + upload + price hint
+ function videoHint() {
+ if (!lastRates || !lastRates.videoTiers) return;
+ if ($('cWatchSecs') && !$('cWatchSecs').options.length)
+ $('cWatchSecs').innerHTML = lastRates.videoTiers.map(t =>
+ '').join('');
+ const tier = lastRates.videoTiers.find(t => t.secs === Number($('cWatchSecs').value)) || lastRates.videoTiers[0];
+ const n = tier ? Math.floor((Number($('cBudget').value) || 0) / tier.cost) : 0;
+ $('cVideoHint').textContent = tier ? (tier.cost + ' credits per completed ' + tier.secs + 's view'
+ + (n ? ' — this budget buys ' + n + ' views' : '') + '. Viewers earn ' + tier.reward + ' credits each, so they watch.') : '';
+ }
+ document.addEventListener('change', e => { if (e.target && e.target.id === 'cWatchSecs') videoHint(); });
+ $('cBudget').addEventListener('input', () => { if ($('cType').value === 'video') videoHint(); });
+ $('cVideoUploadBtn').addEventListener('click', () => $('cVideoFile').click());
+ $('cVideoUrl').addEventListener('change', async () => {
+ const url = $('cVideoUrl').value.trim();
+ $('cVideoInfo').textContent = url ? 'checking video…' : '';
+ cVidDims = url ? await probeVideoDims(url) : null;
+ if (url && !cVidDims) $('cVideoInfo').textContent = 'could not read that video';
+ else { $('cVideoInfo').textContent = ''; showVidOrient(); }
+ });
+ $('cVideoFile').addEventListener('change', async () => {
+ const f = $('cVideoFile').files[0];
+ if (!f) return;
+ $('cVideoInfo').textContent = 'Uploading ' + f.name + '… (large files take a moment)';
+ try {
+ const r = await (await fetch('/api/my/upload', { method: 'POST', headers: { 'Content-Type': f.type }, body: f })).json();
+ if (r.error) { $('cVideoInfo').textContent = r.error; $('cVideoFile').value = ''; return; }
+ $('cVideoUrl').value = r.url;
+ $('cVideoInfo').textContent = f.name + ' uploaded';
+ $('cVideoPrev').hidden = false;
+ $('cVideoPrev').innerHTML = '';
+ cVidDims = await probeVideoDims(r.url); showVidOrient();
+ } catch (e) { $('cVideoInfo').textContent = 'Upload failed. Try again.'; }
+ $('cVideoFile').value = '';
+ });
+ $('createCampBtn').addEventListener('click', busy2($('createCampBtn'), async () => {
+ // in raw mode the source of truth is the textarea; sync it back first
+ let soloBody = $('cSoloEd').innerHTML;
+ if ($('cSoloRaw') && !$('cSoloRaw').hidden) soloBody = $('cSoloRaw').value;
+ const t = $('cType').value;
+ const isVideo = t === 'video', isFeat = t === 'featured';
+ if (isVideo && !cVidDims && $('cVideoUrl').value) cVidDims = await probeVideoDims($('cVideoUrl').value);
+ await api('/api/my/campaigns', { type: t, name: $('cName').value,
+ targetUrl: $('cTarget').value, imageUrl: $('cImage').value, size: $('cSize').value,
+ title: isVideo ? $('cVideoTitle').value : isFeat ? $('cFeatTitle').value : t === 'visits' ? $('cVisitTitle').value : $('cTitle').value,
+ body: t === 'solo' ? soloBody : $('cBody').value,
+ videoUrl: $('cVideoUrl').value, watchSecs: Number($('cWatchSecs').value),
+ videoW: cVidDims ? cVidDims.w : null, videoH: cVidDims ? cVidDims.h : null,
+ days: Number($('cFeatDays').value), startDay: featStartDay,
+ count: Number($('cVisitCount').value),
+ dailyCap: ($('cDailyCap') && (t === 'banner' || t === 'text')) ? Number($('cDailyCap').value) || 0 : 0,
+ geo: [...document.querySelectorAll('.geoTier:checked')].map(x => x.value).join(','),
+ startsAt: ($('cStartAt') && $('cStartAt').value && !isFeat) ? new Date($('cStartAt').value).getTime() : 0,
+ endsAt: ($('cEndAt') && $('cEndAt').value && !isFeat) ? new Date($('cEndAt').value).getTime() : 0,
+ ctaLabel: isVideo ? $('cVideoCta').value : $('cCtaLabel').value,
+ budget: isFeat ? (Number($('cFeatDays').value) * (lastRates.featuredPerDay || 40)) : t === 'visits' ? (Number($('cVisitCount').value) * (lastRates.visitCostPerVisit || 3)) : Number($('cBudget').value) });
+ const schedStart = ($('cStartAt') && $('cStartAt').value && !isFeat) ? new Date($('cStartAt').value) : null;
+ IAP.status(schedStart && schedStart.getTime() > Date.now() ? 'Campaign saved. It starts serving ' + schedStart.toLocaleString([], { dateStyle: 'medium', timeStyle: 'short' }) + '.' : 'Campaign is live. It starts serving right away.', 'ok');
+ // clear EVERY field so no target/creative carries into the next campaign
+ ['cName', 'cBudget', 'cTarget', 'cImage', 'cTitle', 'cBody', 'cCtaLabel',
+ 'cVideoUrl', 'cVideoTitle', 'cVideoCta', 'cVisitTitle', 'cVisitCount', 'cFeatTitle', 'cDailyCap', 'cStartAt', 'cEndAt']
+ .forEach(id => { if ($(id)) $(id).value = ''; });
+ document.querySelectorAll('.geoTier').forEach(x => { x.checked = true; });
+ $('cSoloEd').innerHTML = ''; if ($('cSoloRaw')) $('cSoloRaw').value = '';
+ $('cVideoInfo').textContent = ''; $('cVideoPrev').hidden = true; $('cVideoPrev').innerHTML = '';
+ if ($('edMediaInfo')) $('edMediaInfo').textContent = '';
+ cVidDims = null;
+ await loadCampaigns();
+ }));
+ // defers the busy() lookup to click time (busy is declared below)
+ function busy2(btn, fn) { return (...a) => busy(btn, fn)(...a); }
+
+ // ── verified visits: open a member's site (new tab), dwell, human-check, earn ──
+ const visState = { token: null, id: null, dwell: 8 };
+ async function loadVisitStatus() {
+ try {
+ const st = await (await fetch('/api/my/visits')).json();
+ if (st.error) return;
+ $('vsProgress').textContent = 'today: ' + (st.status.count || 0) + ' / ' + st.status.cap + ' verified visits';
+ $('vsStartBtn').hidden = st.status.count >= st.status.cap;
+ if (st.status.count >= st.status.cap) $('vsBox').innerHTML = 'That\'s today\'s visits. Come back tomorrow.';
+ } catch (e) {}
+ }
+ async function loadVisit() {
+ $('vsCheck').hidden = true; $('vsVisit').hidden = true; $('vsHint').textContent = '';
+ let r = null;
+ try { r = await (await fetch('/api/my/visits')).json(); } catch (e) {}
+ if (!r || !r.ad) {
+ $('vsBox').innerHTML = '' + (r && r.status && r.status.count >= r.status.cap
+ ? 'That\'s today\'s visits. Come back tomorrow.' : 'No verified-visit packs are running right now. Check back soon.') + '';
+ return;
+ }
+ visState.token = r.token; visState.id = r.ad.id; visState.dwell = r.status.dwell || 8;
+ $('vsBox').innerHTML = '' + esc(r.ad.title || 'Member site') + ' Open the site and stay ' + visState.dwell + 's.';
+ const visit = $('vsVisit');
+ visit.href = r.ad.url; visit.hidden = false;
+ $('vsStartBtn').textContent = 'Loading…'; $('vsStartBtn').disabled = true;
+ // opening the site starts the dwell; then we ask the human-check
+ visit.onclick = () => {
+ let left = visState.dwell;
+ $('vsHint').textContent = 'Counting your visit: ' + left + 's';
+ const t = setInterval(async () => {
+ left--;
+ if (left > 0) { $('vsHint').textContent = 'Counting your visit: ' + left + 's'; return; }
+ clearInterval(t);
+ $('vsHint').textContent = 'One quick check to count the visit:';
+ let c = await (await fetch('/api/my/visitchallenge?token=' + visState.token)).json();
+ if (c.early) { await new Promise(r2 => setTimeout(r2, (c.wait || 1) * 1000 + 300)); c = await (await fetch('/api/my/visitchallenge?token=' + visState.token)).json(); }
+ if (c.error) { $('vsHint').textContent = c.error; return; }
+ renderVisitCheck(c);
+ }, 1000);
+ };
+ $('vsStartBtn').textContent = 'Next visit'; $('vsStartBtn').disabled = false;
+ }
+ function renderVisitCheck(c) {
+ $('vsPrompt').textContent = 'Click the ' + c.prompt + ':';
+ const w = $('vsOpts'); w.innerHTML = '';
+ c.options.forEach((em, i) => {
+ const b = document.createElement('button');
+ b.className = 'btn small sec'; b.style.marginRight = '6px'; b.textContent = em;
+ b.addEventListener('click', () => answerVisit(i));
+ w.appendChild(b);
+ });
+ $('vsCheck').hidden = false;
+ }
+ async function answerVisit(i) {
+ const r = await (await fetch('/api/my/visitdone', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ token: visState.token, answer: i }) })).json();
+ if (r.error) {
+ if (r.retry) { const c = await (await fetch('/api/my/visitchallenge?token=' + visState.token)).json(); if (!c.error) return renderVisitCheck(c); }
+ $('vsHint').textContent = r.error; $('vsCheck').hidden = true; return;
+ }
+ $('vsCheck').hidden = true;
+ $('vsHint').textContent = '+' + r.credited + ' credits — visit counted. Load the next one.';
+ $('vsProgress').textContent = 'today: ' + (r.status.count || 0) + ' / ' + (r.status.cap || 0) + ' verified visits';
+ IAP.status('+' + r.credited + ' credits for a verified visit.', 'ok');
+ loadDashboard();
+ }
+ $('vsStartBtn').addEventListener('click', () => loadVisit());
+
+ // ── watch-to-earn videos: escape-proof player, server-clock reward ──
+ const vidState = { token: null, secs: 0, maxSeen: 0, done: false, credited: false };
+ // detected dimensions of the video being created — portrait goes to Shorts, landscape to Watch videos
+ let cVidDims = null;
+ function probeVideoDims(url) {
+ return new Promise(resolve => {
+ if (!url) return resolve(null);
+ const v = document.createElement('video'); v.preload = 'metadata'; v.muted = true;
+ let done = false; const fin = r => { if (!done) { done = true; resolve(r); } };
+ v.onloadedmetadata = () => fin(v.videoWidth && v.videoHeight ? { w: v.videoWidth, h: v.videoHeight } : null);
+ v.onerror = () => fin(null); setTimeout(() => fin(null), 8000); v.src = url;
+ });
+ }
+ function showVidOrient() {
+ const el = $('cVideoInfo'); if (!el) return;
+ if (!cVidDims) return;
+ const portrait = cVidDims.h > cVidDims.w;
+ el.textContent = (el.textContent ? el.textContent + ' · ' : '')
+ + (portrait ? 'portrait — shows in the Shorts reel' : 'landscape — shows in the Watch videos tab');
+ }
+ async function loadVideoStatus() {
+ try {
+ const st = await (await fetch('/api/my/videos?orientation=landscape')).json();
+ if (st.error) return;
+ $('vidProgress').textContent = 'today: ' + (st.status.count || 0) + ' / ' + st.status.cap + ' videos watched';
+ if (st.status.left <= 0) {
+ $('vidBox').innerHTML = 'That is today\'s video set. Come back tomorrow.';
+ $('vidStartBtn').hidden = true;
+ return;
+ }
+ $('vidStartBtn').hidden = false;
+ } catch (e) {}
+ }
+ // leaving the player (other sub-tab, other pane, page hidden) stops the clip: nothing plays or earns in the background (Marty, 2026-09-13)
+ function stopVideo() {
+ const p = $('vidPlayer'); if (!p) return;
+ const was = !!vidState.token && !vidState.done;
+ try { p.pause(); p.ontimeupdate = null; p.onseeking = null; p.removeAttribute('src'); p.load(); } catch (e) {}
+ vidState.token = null; vidState.done = false; vidState.credited = false; vidState.maxSeen = 0;
+ if ($('vidWrap')) $('vidWrap').hidden = true;
+ if ($('vidBox')) { $('vidBox').hidden = false; if (was) $('vidBox').innerHTML = 'Video stopped when you left the tab. Tap Load a video to start a fresh one.'; }
+ if ($('vidStartBtn')) { $('vidStartBtn').disabled = false; $('vidStartBtn').textContent = 'Load a video'; }
+ }
+ document.addEventListener('visibilitychange', () => { if (document.hidden && vidState.token && !vidState.done) stopVideo(); });
+ async function loadVideoAd() {
+ let r = null;
+ try { r = await (await fetch('/api/my/videos?orientation=landscape')).json(); } catch (e) {}
+ if (!r || !r.ad) {
+ // same done screen as Watch ads when the day's videos are finished (Marty, 2026-09-13)
+ const capHit = !!(r && r.status && r.status.left <= 0), allWatched = !!(r && r.allWatched);
+ $('vidBox').innerHTML = (capHit || allWatched)
+ ? '
✓Videos done for today' + (capHit ? 'That is today’s video set (' + r.status.count + ' watched). Fresh videos tomorrow.' : 'You have watched every live video for today; each one pays once a day. New ones appear as members launch video campaigns.') + '
'
+ : 'No member videos are live right now. Check back when a campaign is running.';
+ if ($('vidStartBtn')) $('vidStartBtn').hidden = capHit || allWatched;
+ $('vidBox').hidden = false;
+ $('vidWrap').hidden = true;
+ return;
+ }
+ const ad = r.ad;
+ vidState.token = r.token; vidState.secs = ad.watchSecs; vidState.maxSeen = 0; vidState.done = false; vidState.credited = false;
+ $('vidBox').hidden = true;
+ $('vidWrap').hidden = false;
+ $('vidCta').hidden = true;
+ $('vidHint').textContent = ad.title ? 'Now playing: ' + ad.title : '';
+ const p = $('vidPlayer');
+ p.src = ad.videoUrl;
+ p.currentTime = 0;
+ // escape-proof: no seeking past what's been watched; track max reached
+ p.onseeking = () => { if (p.currentTime > vidState.maxSeen + 0.5) p.currentTime = vidState.maxSeen; };
+ p.ontimeupdate = () => {
+ if (p.currentTime > vidState.maxSeen) vidState.maxSeen = p.currentTime;
+ const left = Math.max(0, Math.ceil(vidState.secs - vidState.maxSeen));
+ $('vidTimer').textContent = left > 0 ? 'Watch ' + left + 's more to earn' : 'Watch time met — finishing…';
+ if (!vidState.done && vidState.maxSeen >= vidState.secs) { vidState.done = true; completeVideo(ad); }
+ };
+ $('vidStartBtn').textContent = 'Playing…';
+ $('vidStartBtn').disabled = true;
+ try { await p.play(); } catch (e) { $('vidStartBtn').disabled = false; $('vidStartBtn').textContent = 'Tap to play'; }
+ $('vidCta').href = ad.ctaUrl;
+ $('vidCta').textContent = ad.ctaLabel || 'Learn more';
+ $('vidCta').hidden = false;
+ }
+ async function completeVideo(ad) {
+ if (vidState.credited) return;
+ vidState.credited = true;
+ try {
+ const r = await (await fetch('/api/my/videowatch', { method: 'POST',
+ headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ token: vidState.token }) })).json();
+ if (r.error) { IAP.status(r.error, 'bad'); $('vidHint').textContent = r.error + (/no longer open|stale/.test(r.error) ? ' Loading a fresh one.' : ''); if (/no longer open|stale/.test(r.error)) setTimeout(() => loadVideoAd(), 1200); }
+ else if (r.credited) { IAP.status('+' + r.credited + ' credits earned for watching.', 'ok'); $('vidHint').textContent = '+' + r.credited + ' credits earned. Load the next one.'; loadDashboard(); }
+ else $('vidHint').textContent = 'That video just ran out of budget — load another.';
+ if (r.status) $('vidProgress').textContent = 'today: ' + (r.status.count || 0) + ' / ' + r.status.cap + ' videos watched';
+ } catch (e) { IAP.status('Could not confirm that watch. Try the next one.', 'bad'); }
+ $('vidStartBtn').disabled = false;
+ $('vidStartBtn').textContent = 'Next video';
+ }
+ $('vidStartBtn').addEventListener('click', () => loadVideoAd());
+ // presence enforcement: pause the watch-to-earn video when the tab/window loses focus,
+ // resume when it comes back — the viewer must stay on the page for the watch to complete
+ document.addEventListener('visibilitychange', () => {
+ const p = $('vidPlayer'); if (!p || !p.src) return;
+ if (document.hidden) p.pause(); else if (!vidState.done) p.play().catch(() => {});
+ });
+ window.addEventListener('blur', () => { const p = $('vidPlayer'); if (p && p.src) p.pause(); });
+ window.addEventListener('focus', () => { const p = $('vidPlayer'); if (p && p.src && !vidState.done) p.play().catch(() => {}); });
+
+ // ── unmissable sponsor-message modal on sign-in ──
+ function showSponsorModal(msg) {
+ if (!$('msgModal')) return;
+ $('mmFrom').textContent = 'A message from ' + (msg.fromName || 'your sponsor');
+ $('mmSubject').textContent = msg.subject || '';
+ $('mmBody').innerHTML = msg.body || ''; // server-sanitized
+ $('msgModal').hidden = false;
+ $('mmAck').onclick = async () => {
+ $('msgModal').hidden = true;
+ try { await fetch('/api/my/messages/' + msg.id + '/read', { method: 'POST' }); } catch (e) {}
+ };
+ }
+
+ // ── coaching: every direct's rung, stalled flag, one-click nudge ──
+ // ── pay it forward: send POL from the sponsor's own wallet to a downline's linked address ──
+ async function pif(email, name, address) {
+ let suggest = 25;
+ try { const { products } = await (await fetch('/api/catalog')).json(); const p25 = (products || []).find(p => p.priceCents === 2500); if (p25 && p25.costWei) suggest = Math.ceil(Number(p25.costWei) / 1e18) + 3; } catch (e) {}
+ const amt = await IAP.ask({ title: 'Pay it forward', text: 'Send POL from your wallet to ' + name + ' (' + address.slice(0, 6) + '…' + address.slice(-4) + ') for their first package.\nSuggested: the $25 package plus fees. Amount in POL:', type: 'number', value: String(suggest), ok: 'Send POL' });
+ if (amt === null) return;
+ const pol = Number(amt); if (!(pol > 0)) { IAP.status('Enter an amount in POL.', 'bad'); return; }
+ try {
+ IAP.status('Confirm the transfer in your wallet…', 'ok');
+ const wei = (BigInt(Math.round(pol * 1e6)) * 10n ** 12n).toString();
+ const hash = await IAPWallet.sendPol(address, wei);
+ await api('/api/my/gift', { email, tx: hash, pol });
+ IAP.status('Sent ' + pol + ' POL to ' + name + '. They have been told, with the proof link.', 'ok');
+ playSound && playSound('chaching');
+ } catch (e) { IAP.status('Transfer not sent: ' + ((e && e.message) || e), 'bad'); }
+ }
+ // ── holding tank: waiting members, adopt, my open adoptions ──
+ const ago = ts => { if (!ts) return 'never'; const d = Math.floor((Date.now() - ts) / 86400000); return d === 0 ? 'today' : d === 1 ? 'yesterday' : d + ' days ago'; };
+ async function loadTank() {
+ const el = $('tankList'); if (!el) return;
+ try {
+ const r = await (await fetch('/api/my/tank')).json();
+ if (r.error) { el.innerHTML = ''; return; }
+ $('tankCap').textContent = r.cap; $('tankTtl').textContent = r.ttlDays;
+ $('tankSub').textContent = r.waiting.length ? r.waiting.length + ' waiting' : 'nobody waiting right now';
+ const why = $('tankWhy'); why.hidden = r.eligible; why.innerHTML = r.eligible ? '' : 'not yet ' + esc(r.reason);
+ $('tankMine').innerHTML = r.mine.length ? '
').join('');
+ el.querySelectorAll('[data-adopt]').forEach(b => b.addEventListener('click', async () => {
+ const note = await IAP.ask({ title: 'Adopt ' + b.dataset.aname, text: 'Your first message to ' + b.dataset.aname + ' (sent as a chat and an email):', type: 'textarea', ok: 'Adopt and send', value: 'Hi, I picked you up from the LinkSpin holding tank so you have a sponsor who will actually help. Reply here and I will walk you through the first three steps.' });
+ if (note === null) return;
+ try { const rr = await api('/api/my/tank/adopt', { who: b.dataset.adopt, note }); IAP.status('You are now the sponsor for ' + rr.name + '. Chat and email sent.', 'ok'); loadTank(); loadCoach(); }
+ catch (e) { IAP.status(e.message, 'bad'); }
+ }));
+ } catch (e) {}
+ }
+ async function loadCoach() {
+ loadTank();
+ try {
+ const r = await (await fetch('/api/my/coach')).json();
+ const el = $('coachList'); if (!el || r.error) return;
+ const d = r.directs || [];
+ $('coachSummary').innerHTML = d.length ? '' + d.length + ' direct' + (d.length === 1 ? '' : 's') + ' · ' + r.stalled + ' quiet for 3+ days' + (r.stalled ? ' · start at the top' : '') : '';
+ if (!d.length) { el.innerHTML = '
No directs yet. When someone joins through your link they show up here with their next step.
';
+ }
+ async function loadPipeline() {
+ try {
+ const r = await (await fetch('/api/my/pipeline')).json();
+ if (r.error) { IAP.status(r.error, 'bad'); return; }
+ if (!r.live) {
+ $('pipeSoon').hidden = false; $('pipeLive').hidden = true;
+ $('pipeSoonEta').textContent = r.eta ? 'Opens ' + r.eta + '. It is on the roadmap so you can see what is coming and when.' : 'It is on the roadmap so you can see what is coming and when.';
+ return;
+ }
+ PIPE = r; $('pipeSoon').hidden = true; $('pipeLive').hidden = false;
+ const badge = $('pipeBadge'); if (badge) { const n = r.counts.due + r.counts.stalled; badge.hidden = !n; badge.textContent = n > 9 ? '9+' : n; }
+ $('pipeDueCount').hidden = !r.due.length; $('pipeDueCount').textContent = r.due.length;
+ $('pipeDue').innerHTML = r.due.length ? '
Nothing due. Set a follow-up date on any card and it shows up here.
';
+ $('pipeSummary').textContent = r.counts.total ? r.counts.total + ' people on your board' + (r.counts.stalled ? ', ' + r.counts.stalled + ' stalled' : '') + '. Cards move on their own when something happens on the ledger; open one to add a note, a follow-up date or a tag.' : 'Nobody on your board yet. Add prospects on My line, and everyone who joins through your link appears here on their own.';
+ $('pipeBoard').innerHTML = r.columns.map(col => '
Glad you are in. Three things today, in this order:
Pick your username on the Profile tab (it becomes your link).
Wallet tab: Connect and link wallet, then Switch on payouts. Both are free.
Copy your invite link from My line and send it to one person.
Reply here if you get stuck on any of them. That is what I am here for.
' },
+ { label: 'Switch on payouts', subject: 'One free step so nothing passes you by', html: '
Quick reminder: if payouts are not switched on yet, do it now on the Wallet tab. One free transaction.
The contract locks each buyer to their sponsor at their first purchase, and payouts only route to wallets that are switched on. Ready early and you never miss one.
' },
+ { label: 'The $10 test', subject: 'See a payout land in real time', html: '
Want to see the whole thing work? Buy the $10 package on Buy packages and watch the live ledger while you do it. You will see your credits mint and the split go out in the same transaction.
When you are ready to count as a qualifying buyer for me, the $20 Activation package is the one.
' },
+ { label: 'Qualified Start', subject: 'How to open level 2 today with your own positions', html: '
You can be your own first buyers, openly. On Buy packages, the Qualified Start card lets you link a second wallet you own as a position. When it buys a $25 package, it counts as a qualifying buyer, half comes straight back to your main wallet, and the credits pool with yours.
Two positions open level 2 the same day. The three Qualified Start videos in Training show every click.
' },
+ { label: 'Share your link', subject: 'One conversation a day is the whole job', html: '
Promo tools has posts, texts and emails that already carry your link. Pick one and send it to one person today.
Do not wait for the perfect moment. Nobody who waited ever built a line.
' }
+ ];
+ (function () {
+ const w = $('bcTemplates'); if (!w) return;
+ w.innerHTML = BC_TEMPLATES.map((t, i) => '').join('');
+ w.querySelectorAll('[data-bct]').forEach(b => b.addEventListener('click', () => { const t = BC_TEMPLATES[Number(b.dataset.bct)]; $('bcSubject').value = t.subject; $('bcEd').innerHTML = t.html; $('bcEd').focus(); }));
+ })();
+ // ── Qualified Start calculator ──
+ (function () {
+ const n = $('qcN'), pk = $('qcPkg'), out = $('qcOut'); if (!n || !pk || !out) return;
+ const CR = { 25: 2500, 50: 5000, 100: 10000, 250: 25000, 500: 50000 }; // flat credits = cents (Marty 2026-10-07)
+ const calc = () => {
+ const k = Math.max(1, Math.min(10, Number(n.value) || 1)), usd = Number(pk.value) || 25;
+ const gross = k * usd, back = gross / 2, net = gross - back, credits = k * (CR[usd] || 0);
+ const level = k >= 5 ? 'Level 3 open (and level 2): the Nexus badge, wall position 3, full 50 / 20 / 10' : k >= 2 ? 'Level 2 open: 20% on your directs\' buyers, wall position 2' : 'Counts as one qualifying buyer. One more opens level 2.';
+ out.innerHTML = '
$' + gross + ' out across ' + k + ' position' + (k === 1 ? '' : 's') + ' $' + back + ' back to your main wallet in the same transactions (the 50% direct-sponsor share) $' + net + ' net, plus a little POL for gas in each wallet
'
+ + '
' + credits.toLocaleString() + ' credits pooled for your own ads ' + level + ' The 20% and 10% shares go to your upline if they are qualified, otherwise to the platform.
').join('');
+ // opening the pane marks them read
+ for (const i of r.items) if (!i.read) fetch('/api/my/messages/' + i.id + '/read', { method: 'POST' }).catch(() => {});
+ } catch (e) {}
+ }
+ // broadcast composer editor (its own small rich editor, server sanitizes)
+ document.querySelectorAll('[data-bc]').forEach(b =>
+ b.addEventListener('click', () => { $('bcEd').focus(); document.execCommand(b.dataset.bc, false, null); }));
+ document.querySelectorAll('[data-bcblock]').forEach(b =>
+ b.addEventListener('click', () => { $('bcEd').focus(); document.execCommand('formatBlock', false, b.dataset.bcblock); }));
+ if ($('bcLinkBtn')) $('bcLinkBtn').addEventListener('click', async () => {
+ const sel = window.getSelection(); const range = sel && sel.rangeCount ? sel.getRangeAt(0).cloneRange() : null;
+ const u = await IAP.ask({ title: 'Insert link', text: 'Link URL (https://…)', placeholder: 'https://', ok: 'Insert' });
+ if (u) { $('bcEd').focus(); if (range) { sel.removeAllRanges(); sel.addRange(range); } document.execCommand('createLink', false, u); }
+ });
+ if ($('bcSendBtn')) $('bcSendBtn').addEventListener('click', busy2($('bcSendBtn'), async () => {
+ const r = await api('/api/my/broadcast', { scope: $('bcScope').value, subject: $('bcSubject').value, body: $('bcEd').innerHTML });
+ IAP.status('Broadcast sent to ' + r.sent + ' member' + (r.sent === 1 ? '' : 's') + '.', 'ok');
+ $('bcSubject').value = ''; $('bcEd').innerHTML = '';
+ $('bcHint').textContent = 'Sent. You can send your next broadcast in 24 hours.';
+ }));
+
+ // ── solo-ads inbox: list, read view, dwell-gated read reward ──
+ let ibTimer = null;
+ function setInboxBadge(n) {
+ for (const id of ['inboxBadge', 'inboxBadge2']) {
+ const b = $(id);
+ if (b) { b.hidden = !n; b.textContent = n; }
+ }
+ }
+ // Earn credits sub-tabs: Watch ads | Inbox
+ let earnSub = 'watch';
+ function setEarnSub(which) {
+ earnSub = ['inbox', 'videos', 'visits'].includes(which) ? which : 'watch';
+ if (earnSub !== 'videos' && vidState.token) stopVideo();
+ const w = $('earn-watch'), i = $('earn-inbox'), v = $('earn-videos'), vs = $('earn-visits');
+ if (w) w.hidden = earnSub !== 'watch';
+ if (i) i.hidden = earnSub !== 'inbox';
+ if (v) v.hidden = earnSub !== 'videos';
+ if (vs) vs.hidden = earnSub !== 'visits';
+ document.querySelectorAll('.subtabs [data-earn]').forEach(b =>
+ b.classList.toggle('on', b.dataset.earn === earnSub));
+ if (earnSub === 'inbox') loadInbox();
+ else if (earnSub === 'videos') loadVideoStatus();
+ else if (earnSub === 'visits') loadVisitStatus();
+ else earnRefresh();
+ }
+ document.querySelectorAll('.subtabs [data-earn]').forEach(b =>
+ b.addEventListener('click', () => setEarnSub(b.dataset.earn)));
+ // promo toolkit: badge tiers + the AI Copy Engine (Marty, 2026-09-14)
+ let tkState = null;
+ async function loadToolkit() {
+ try {
+ const r = await (await fetch('/api/my/toolkit')).json(); if (r.error) return; tkState = r;
+ const esc = t => String(t == null ? '' : t).replace(/[&<>"]/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"' }[c]));
+ const names = { free: 'Free', spark: 'Spark', surge: 'Surge', circuit: 'Circuit', nexus: 'Nexus' };
+ $('tkTierLine').textContent = 'you are at ' + names[r.tier];
+ $('tkTiers').innerHTML = r.tiers.map(t => '
' + esc(t.name) + (t.reached ? ' ✓' : '') + '
' + (t.reached ? esc(t.blurb) : 'Unlocks when you ' + esc(t.needText)) + '
' + t.items.map(i => '
' + esc(i.t) + '
').join('') + '
' + (t.reached ? '' : '
locked
') + '
').join('');
+ $('tkLocked').hidden = r.unlocked; $('tkForm').hidden = !r.unlocked;
+ if (!r.unlocked) { $('tkLocked').textContent = 'Unlocks at Surge: your first qualifying buyer of a $25 or larger package. Then it writes posts, DMs, follow-ups, objection replies, emails and story posts in your name, with your link, inside the honesty rules. ' + (r.tier === 'free' ? 'Step one is switching on payouts.' : 'You are one buyer away.'); $('tkUsage').textContent = 'locked'; renderTkTools(r); return; }
+ $('tkUsage').textContent = r.freeLeft + ' free this month · then ' + r.cost + ' credits each · you have ' + r.available.toLocaleString() + ' credits';
+ $('tkCostLine').textContent = r.freeLeft > 0 ? 'This one is free (' + r.freeLeft + ' left this month).' : 'This one costs ' + r.cost + ' credits from your earned pool.';
+ if (!$('tkKind').options.length) { $('tkKind').innerHTML = r.kinds.map(k => '').join(''); $('tkAngle').innerHTML = r.angles.map(a => '').join(''); }
+ renderTkTools(r);
+ $('tkHistory').innerHTML = r.history.length ? '
').join('') : '';
+ } catch (e) { console.error('toolkit', e); }
+ }
+ // the rest of the ladder: Spark templates + handout, Circuit Video Maker + split tester, Nexus Leader Ops
+ const tkEsc = t => String(t == null ? '' : t).replace(/[&<>"]/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"' }[c]));
+ const tkRank = { free: 0, spark: 1, surge: 2, circuit: 3, nexus: 4 };
+ async function tkPost(url, body) { const r = await (await fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body || {}) })).json(); if (r.error) { IAP.status(r.error, 'bad'); return null; } return r; }
+ function renderTkTools(r) {
+ const at = tkRank[r.tier] || 0;
+ // Spark
+ const spark = at >= 1; $('tkSparkLocked').hidden = spark; $('tkSparkBody').hidden = !spark;
+ if (!spark) $('tkSparkLocked').textContent = 'Unlocks at Spark: switch on payouts in the Wallet tab. Then one tap builds a banner or text campaign aimed at your link, and you get a printable handout with your QR.';
+ else { $('tkHandoutLine').hidden = !r.handoutUrl; if (r.handoutUrl) $('tkHandout').href = r.handoutUrl; }
+ // Circuit
+ const circ = at >= 3; $('tkCircuitLocked').hidden = circ; $('tkCircuitBody').hidden = !circ;
+ if (!circ) $('tkCircuitLocked').textContent = 'Unlocks at Circuit: two qualifying buyers in your line. Then every promo video gets your own end card and QR, and the split tester shows which join angle pulls for you.';
+ else { loadTkVideos(r); loadTkSplit(); }
+ // Nexus
+ const nex = at >= 4; $('tkNexusLocked').hidden = nex; $('tkNexusBody').hidden = !nex;
+ if (!nex) $('tkNexusLocked').textContent = 'Unlocks at Nexus: five qualifying buyers. Then you get team triage across three levels with one-click nudges, AI-drafted team broadcasts, credit grants to your people, a co-branded join page and your own partner code.';
+ else { loadTkTeam(); renderTkPartner(r); }
+ }
+ let tkVidTimer = null;
+ async function loadTkVideos(r) {
+ const box = $('tkVideos');
+ if (!r.videoMaker) { box.innerHTML = '
The Video Maker is warming up on the server. Check back shortly.
'; return; }
+ if (!r.username) { box.innerHTML = '
Pick a username first (Profile); it goes on the end card.
Code ' + tkEsc(pk.code) + ' gives ' + pk.credits + ' welcome credits, funded from your earned pool at each redemption. Redeemed ' + pk.uses + ' times.
Invite link with the code: ' + tkEsc(pk.link) + '
Your partner kit page (for list owners and site owners you talk to): ' + tkEsc(pk.kit) + '
'
+ : '
Give your recruits a welcome bonus under your own code. Each redemption moves the credits from your earned pool to theirs, so it only costs you when it works. Then hand partners the kit page, which sends their deals under you.
';
+ }
+ document.addEventListener('click', async ev => {
+ const b = ev.target.closest('[data-tpl],[data-mkvid],[data-copyvid],[data-nudge],[data-copy],#tkPcGo,#tkGrantGo,#tkDraftBc,[data-sendnudge]'); if (!b) return;
+ if (b.dataset.tpl) { b.disabled = true; const r = await tkPost('/api/my/toolkit/template', { kind: b.dataset.tpl, budget: Number($('tkTplBudget').value) }); b.disabled = false; if (r) { IAP.status('Campaign "' + r.name + '" created with ' + r.budget + ' credits. It is under Campaigns.', 'ok'); loadDashboard(); } return; }
+ if (b.dataset.mkvid) { b.disabled = true; const r = await tkPost('/api/my/toolkit/video', { slug: b.dataset.mkvid }); if (r) { IAP.status(r.status === 'done' ? 'Already made.' : 'Rendering. It appears here in about a minute.', 'ok'); loadTkVideos(tkState); } else b.disabled = false; return; }
+ if (b.dataset.copyvid || b.dataset.copy) { try { await navigator.clipboard.writeText(b.dataset.copyvid || b.dataset.copy); IAP.status('Copied.', 'ok'); } catch (e) { IAP.status('Copy failed; select it by hand.', 'bad'); } return; }
+ if (b.dataset.nudge) { const row = b.closest('.tk-team'); const old = row.querySelector('.tk-nudge'); if (old) { old.remove(); return; } const box = document.createElement('div'); box.className = 'tk-nudge'; box.innerHTML = '
Lands in their inbox and their email.
'; box.querySelector('textarea').value = b.dataset.say; row.appendChild(box); return; }
+ if (b.dataset.sendnudge) { const box = b.closest('.tk-nudge'); b.disabled = true; const r = await tkPost('/api/my/toolkit/nudge', { email: b.dataset.sendnudge, text: box.querySelector('textarea').value }); b.disabled = false; if (r) { IAP.status('Sent.', 'ok'); box.remove(); } return; }
+ if (b.id === 'tkGrantGo') { b.disabled = true; const r = await tkPost('/api/my/toolkit/grant', { email: $('tkGrantTo').value, credits: Number($('tkGrantN').value) }); b.disabled = false; if (r) { IAP.status(r.credits + ' credits moved to ' + r.toName + '.', 'ok'); loadToolkit(); loadDashboard(); } return; }
+ if (b.id === 'tkPcGo') { b.disabled = true; const r = await tkPost('/api/my/toolkit/promo', { code: b.dataset.code || ($('tkPcCode') ? $('tkPcCode').value : ''), credits: Number($('tkPcN').value) }); b.disabled = false; if (r) { IAP.status('Code ' + r.code + ' is live: ' + r.credits + ' welcome credits.', 'ok'); loadToolkit(); } return; }
+ if (b.id === 'tkDraftBc') { if (!tkState || !tkState.unlocked) return; $('tkKind').value = 'broadcast'; $('tkBrief').placeholder = 'What should the team focus on this week?'; $('tkEngine').scrollIntoView({ behavior: 'smooth', block: 'start' }); $('tkBrief').focus(); IAP.status('Pick a focus, hit Write it, then Send to my team.', 'ok'); return; }
+ });
+ $('tkKind') && $('tkKind').addEventListener('change', () => { if ($('tkSendBc')) $('tkSendBc').hidden = $('tkKind').value !== 'broadcast'; });
+ async function tkSendBroadcast() {
+ const txt = $('tkText').value || ''; const m = /^\s*Subject:\s*(.+)\n+([\s\S]+)$/.exec(txt);
+ const subject = m ? m[1].trim() : 'A note from your sponsor', body = (m ? m[2] : txt).trim();
+ if (!(await IAP.confirmBox('Send this to everyone in your three levels? One broadcast a day.', { title: 'Team broadcast', ok: 'Send' }))) return;
+ const r = await tkPost('/api/my/broadcast', { subject, body: '
Pooled credits: ' + (r.totalCredits || 0).toLocaleString() + '' + (r.credited ? ' plus ' + r.credited.toLocaleString() + ' credited to your account (spends from any position)' : '') + '. A campaign budget spends from one position at a time.
' : '');
+ if ($('qsList')) $('qsList').innerHTML = html;
+ // Wallet tab: live POL balance of the linked wallet, and which package it covers
+ const wb = $('walletBal');
+ if (wb && r.main && r.main.address && r.main.balanceWei != null) {
+ const polN = Number(BigInt(r.main.balanceWei) / 10n ** 14n) / 10000;
+ const usd = r.polUsd ? polN * r.polUsd : 0;
+ const pkgs = [5, 20, 50, 100, 250];
+ const covers = r.polUsd ? pkgs.filter(p => usd >= p * 1.06 + 0.05) : [];
+ wb.hidden = false;
+ wb.innerHTML = 'Wallet balance: ' + polN.toLocaleString(undefined, { maximumFractionDigits: 2 }) + ' POL' + (usd ? ' (about $' + usd.toLocaleString(undefined, { maximumFractionDigits: 0 }) + ')' : '')
+ + (r.polUsd ? ' ' + (covers.length ? 'Enough for the $' + covers[covers.length - 1] + ' package with gas to spare.' : 'Not enough for the $5 package yet. Buy POL with a card on the Buy packages tab, or send POL to this wallet.') + (covers.length && covers.length < pkgs.length ? ' Top up for the $' + pkgs[covers.length] + ' package.' : '') + '' : '');
+ }
+ if ($('posList')) $('posList').innerHTML = html;
+ if ($('posCard')) $('posCard').hidden = !list.length;
+ // "Buy from" picker: main + every position
+ const sel = $('buyFrom');
+ if (sel) {
+ const keep = sel.value;
+ sel.innerHTML = ''
+ + list.map((p, i) => '').join('');
+ noPayoutAddrs = new Set(list.filter(p => p.noPayout).map(p => p.address.toLowerCase())); if (r.main && r.main.noPayout && r.main.address) noPayoutAddrs.add(r.main.address.toLowerCase());
+ if (keep && [...sel.options].some(o => o.value === keep)) sel.value = keep;
+ $('buyFromWrap').hidden = !list.length;
+ }
+ document.querySelectorAll('[data-unlink]').forEach(b => b.addEventListener('click', async () => {
+ if (!(await IAP.confirmBox('Unlink ' + short(b.dataset.unlink) + ' from your account?', { title: 'Unlink position', ok: 'Unlink' }))) return;
+ try { await api('/api/my/positions/remove', { address: b.dataset.unlink }); IAP.status('Position unlinked.', 'ok'); loadPositions(); }
+ catch (e) { IAP.status(e.message, 'bad'); }
+ }));
+ } catch (e) {}
+ }
+ if ($('qsAddBtn')) $('qsAddBtn').addEventListener('click', busy2($('qsAddBtn'), async () => {
+ const me = await (await fetch('/api/me')).json();
+ if (!me.address) throw new Error('Link your main wallet first (Wallet tab), then add positions under it.');
+ if (!me.memberId) throw new Error('Switch on payouts for your main wallet first (Wallet tab). Positions register under your member number.');
+ if (!(await IAP.confirmBox('Your wallet will ask which account to connect. Tick ONLY the new account (not ' + short(me.address) + '), then sign once.\n\nIf you have not created the extra account yet: MetaMask, account menu, Add account. Trust or SafePal: switch wallet.\n\nReady?', { title: 'Add a position', ok: 'Ready' }))) return;
+ IAP.status('Pick the new account in your wallet, then sign once…');
+ const r = await IAPWallet.signIn({ asPosition: true, pick: true });
+ $('qsHint').textContent = 'Added ' + short(r.address) + '. Now choose it under "Buy from" and buy a $25 or larger package.';
+ IAP.status('Position added: ' + short(r.address) + '. Pick it under "Buy from" above and buy a $25+ package to count it.', 'ok');
+ await loadPositions();
+ const sel = $('buyFrom'); if (sel) sel.value = r.address.toLowerCase();
+ try { $('buyFrom').scrollIntoView({ behavior: 'smooth', block: 'center' }); } catch (e) {}
+ }));
+ async function loadBuyTiles() {
+ try {
+ const { products } = await (await fetch('/api/catalog')).json();
+ const wrap = $('boTiles');
+ wrap.innerHTML = '';
+ for (const p of products) {
+ const bonus = p.creditAmount - p.priceCents;
+ const div = document.createElement('div');
+ div.className = 'tile' + (p.priceCents === 5000 ? ' hot' : '');
+ div.innerHTML = '
' + (p.costWei ? IAP.fmtPol(p.costWei) + ' POL right now' : 'paused') + '
'
+ + '';
+ wrap.appendChild(div);
+ }
+ wrap.querySelectorAll('button[data-id]').forEach(b => b.addEventListener('click', async () => {
+ try {
+ b.disabled = true;
+ // the buyer's credits are read by the member id of their LINKED wallet.
+ // If they only connected a wallet (e.g. for the faucet) but never linked
+ // it, link it first (one signature) so the purchase's credits show up.
+ // retry these through transient failures — mobile drops in-flight
+ // fetches when the page returns from the wallet app-switch
+ const jretry = async url => { let err; for (let i = 0; i < 4; i++) { try { return await (await fetch(url)).json(); } catch (e) { err = e; await new Promise(s => setTimeout(s, 500 * (i + 1))); } } throw err; };
+ const meNow = await jretry('/api/me');
+ // which of the member's wallets is buying: the main wallet (default) or a
+ // linked position (Qualified Start). A position registers under the main
+ // member id on its first buy, so its sponsor is always this member.
+ const fromSel = $('buyFrom');
+ const fromPos = (fromSel && !$('buyFromWrap').hidden && fromSel.value && fromSel.value !== 'main') ? fromSel.value.toLowerCase() : null;
+ if (fromPos && !meNow.memberId) { IAP.status('Switch on payouts for your main wallet first (Wallet tab), so this position can register under you.', 'bad'); return; }
+ if (noPayoutAddrs.has(fromPos || String(meNow.address || '').toLowerCase())) { IAP.status('This position is kept for linkage only. A purchase from it would pay a retired wallet. Buy from your main wallet or another position.', 'bad'); return; }
+ if (!fromPos && !meNow.address) {
+ IAP.status('Link your wallet first — one quick signature…');
+ await IAPWallet.signIn();
+ }
+ const wantAddr = fromPos || (meNow.address ? meNow.address.toLowerCase() : null);
+ if (wantAddr) { // never buy from a wallet other than the one selected: a stray wallet would register a brand-new member
+ await IAPWallet.connect();
+ let cur = String(await IAPWallet.activeAddress() || '').toLowerCase();
+ if (cur !== wantAddr) {
+ IAP.status('Pick ' + wantAddr.slice(0, 6) + '…' + wantAddr.slice(-4) + ' in your wallet\'s account picker…');
+ cur = String(await IAPWallet.pickAccount() || '').toLowerCase();
+ }
+ if (cur !== wantAddr) throw new Error('Your wallet connected as ' + cur.slice(0, 6) + '…' + cur.slice(-4) + ' but you chose ' + wantAddr.slice(0, 6) + '…' + wantAddr.slice(-4) + '. Switch accounts in your wallet app and try again.');
+ }
+ const spNow = fromPos ? { sponsorId: meNow.memberId } : await jretry('/api/sponsor?intent=buy');
+ if (!fromPos && !meNow.memberId && spNow.sponsorBlocked) { IAP.status(sponsorHoldText(spNow), 'bad'); return; } // first activation must not hand a sponsored member to the company
+ // pre-flight: stop early if the POL is not there. Trust Wallet also hard-blocks any
+ // transaction that spends most of the balance ("drain your wallet"), so Trust users
+ // get a heads-up first; other wallets go straight to the confirmation.
+ try {
+ const need = BigInt(b.dataset.cost) + BigInt(b.dataset.cost) / 50n; // same 2% pad as buy()
+ const bal = await IAPWallet.balance(wantAddr || IAPWallet.address() || meNow.address);
+ if (bal < need) {
+ IAP.status('That wallet holds ' + IAP.fmtPol(bal.toString()) + ' POL, but this package needs about ' + IAP.fmtPol(need.toString()) + ' POL plus a little for gas. Top it up and try again.', 'bad');
+ return;
+ }
+ const pct = Number(need * 100n / bal);
+ const isTrust = /trust/i.test(IAPWallet.walletName() || '');
+ if (isTrust && pct > 55 && !(await IAP.confirmBox('Heads up for Trust Wallet users: this purchase uses about ' + pct + '% of the POL in your wallet, and Trust Wallet refuses transactions that spend most of the balance (it shows a "drain your wallet" warning with only Stop and go back).' + '\n\n' + 'Options: pick a smaller package first, add some POL, or connect a different wallet (MetaMask, Phantom, SafePal). Extra POL always stays yours.' + '\n\n' + 'Try it anyway?', { title: 'Trust Wallet check', ok: 'Buy anyway', cancel: 'Pause' }))) {
+ IAP.status('Purchase paused. Pick a smaller package, add POL, or connect another wallet, then try again.', 'ok');
+ return;
+ }
+ } catch (e) { /* balance read failed: let the wallet decide */ }
+ IAP.status('Confirm the purchase in your wallet…');
+ const r = await IAPWallet.buy(Number(b.dataset.id), spNow.sponsorId || 0, b.dataset.cost);
+ if (r.status !== '0x1' && r.receipt && r.receipt.status !== '0x1') throw new Error('Transaction reverted.');
+ IAP.status(fromPos ? 'Purchase settled on-chain. That position now counts toward your qualification, and its credits pool with yours.' : 'Purchase settled on-chain. Credits are in your account.', 'ok');
+ await render();
+ loadBuyTiles();
+ } catch (e) { IAP.status('Purchase failed: ' + ((e && e.message) || e), 'bad'); }
+ finally { b.disabled = false; }
+ }));
+ // brand new to crypto? point to the wallet guide (buy POL on any exchange or on-ramp, send it to your own wallet)
+ const cta = document.createElement('div');
+ cta.style.cssText = 'grid-column:1/-1;margin-top:10px;text-align:center';
+ cta.innerHTML = '
New to crypto? Buy POL with a card on any major exchange or on-ramp, then send it to your own wallet on the Polygon network. This site never touches your money.
'
+ + 'Wallet help';
+ wrap.appendChild(cta);
+ } catch (e) {}
+ }
+ loadBuyTiles();
+
+ // ── earn-by-viewing: daily ad set with dwell, then claim ──
+ const earnState = { types: ['banner', 'text'], i: 0, timer: null };
+ async function earnRefresh() {
+ try {
+ const st = await (await fetch('/api/my/earn')).json();
+ if (st.error) return null;
+ $('earnProgress').textContent = 'today: ' + st.views + ' / ' + st.target + ' ads viewed';
+ $('earnBalance').textContent = (st.earnedAvailable != null ? st.earnedAvailable : st.earned) + ' earned credits available' + (st.reserved ? ' · ' + st.reserved + ' in live campaigns' : '');
+ const done = st.views >= st.target;
+ $('earnClaimBtn').hidden = !(done && !st.claimed);
+ if (st.claimed) {
+ $('earnHint').textContent = 'Claimed for today' + (st.streakDay > 1 ? ' (streak day ' + st.streakDay + ')' : '') + '. Tomorrow\'s claim pays ' + st.nextClaim + ' credits if you come back.';
+ // after the set (Marty, 2026-09-12): keep going with verified visits, and turn the credits into a campaign
+ const box = $('earnAdBox');
+ if (box) box.innerHTML = '
✓Ads done for todayToday\'s set is viewed and claimed. Fresh ads tomorrow.'
+ + '
'; }
+ }
+
+ async function openConvo(email, name) {
+ if (!email) return;
+ CHAT_OTHER = email; CHAT_LASTID = 0;
+ const dr = $('chatDrawer'); if (!dr) return;
+ dr.hidden = false; $('chatThreads').hidden = true; $('chatConvo').hidden = false;
+ $('chatBack').hidden = false; $('chatDot').hidden = false;
+ $('chatTitle').textContent = name || email; $('chatStatus').textContent = '…';
+ $('chatMsgs').innerHTML = ''; $('chatBanner').hidden = true;
+ $('chatInput').disabled = false; $('chatSend').disabled = false;
+ await pullThread(true); startPoll();
+ setTimeout(() => { const i = $('chatInput'); if (i) i.focus(); }, 60);
+ }
+
+ function renderMsgs(msgs) {
+ const box = $('chatMsgs'); if (!box) return;
+ const atBottom = box.scrollTop + box.clientHeight >= box.scrollHeight - 60;
+ for (const m of msgs) {
+ if (m.id <= CHAT_LASTID) continue;
+ CHAT_LASTID = Math.max(CHAT_LASTID, m.id);
+ const d = document.createElement('div');
+ d.className = 'cbub ' + (m.fromMe ? 'me' : 'them');
+ d.textContent = m.body;
+ const t = document.createElement('span'); t.className = 'ct-time';
+ t.textContent = new Date(m.sent).toLocaleTimeString([], { hour: 'numeric', minute: '2-digit' });
+ d.appendChild(t); box.appendChild(d);
+ }
+ if (atBottom) box.scrollTop = box.scrollHeight;
+ }
+
+ async function pullThread(reset) {
+ if (!CHAT_OTHER) return;
+ try {
+ const r = await (await fetch('/api/my/chat/thread?with=' + encodeURIComponent(CHAT_OTHER) + '&after=' + (reset ? 0 : CHAT_LASTID))).json();
+ if (r.error) { $('chatBanner').hidden = false; $('chatBanner').textContent = r.error; return; }
+ if (reset) { $('chatMsgs').innerHTML = ''; CHAT_LASTID = 0; }
+ renderMsgs(r.messages || []);
+ $('chatDot').className = 'pres-dot' + (r.online ? ' on' : '');
+ $('chatStatus').textContent = r.online ? 'active now' : (r.available ? 'away · will get your note' : 'not taking live chats · leave a note');
+ CHAT_CANMUTE = !!r.canMute; CHAT_IMUTE = !!r.iMute;
+ const mb = $('chatMute'); mb.hidden = !CHAT_CANMUTE; mb.textContent = CHAT_IMUTE ? 'Unmute' : 'Mute';
+ const blocked = !!r.blocked;
+ $('chatInput').disabled = blocked; $('chatSend').disabled = blocked;
+ if (blocked) { $('chatBanner').hidden = false; $('chatBanner').textContent = 'They are not accepting messages from you right now.'; }
+ else if (CHAT_IMUTE) { $('chatBanner').hidden = false; $('chatBanner').textContent = 'You muted this member. Unmute to let them message you again.'; }
+ else $('chatBanner').hidden = true;
+ } catch (e) {}
+ }
+
+ async function chatSend() {
+ const inp = $('chatInput'); if (!inp) return;
+ const text = inp.value.trim(); if (!text || !CHAT_OTHER) return;
+ $('chatSend').disabled = true;
+ try {
+ const r = await api('/api/my/chat/send', { to: CHAT_OTHER, body: text });
+ inp.value = ''; autoGrow(inp); renderMsgs([r.message]);
+ const box = $('chatMsgs'); box.scrollTop = box.scrollHeight;
+ } catch (e) { IAP.status(e.message || 'Could not send.', 'bad'); }
+ finally { $('chatSend').disabled = false; inp.focus(); }
+ }
+
+ async function toggleMute() {
+ if (!CHAT_OTHER) return;
+ try { const r = await api('/api/my/chat/mute', { email: CHAT_OTHER, muted: !CHAT_IMUTE }); CHAT_IMUTE = r.muted; $('chatMute').textContent = CHAT_IMUTE ? 'Unmute' : 'Mute'; pullThread(false); }
+ catch (e) { IAP.status(e.message, 'bad'); }
+ }
+
+ (function chatInit() {
+ if (!$('chatDrawer')) return;
+ const on = (id, ev, fn) => { const el = $(id); if (el) el.addEventListener(ev, fn); };
+ on('chatMenuBtn', 'click', e => { if (e && e.preventDefault) e.preventDefault(); openThreads(); });
+ on('chatClose', 'click', closeDrawer);
+ on('chatBack', 'click', openThreads);
+ on('chatMute', 'click', toggleMute);
+ on('chatSend', 'click', chatSend);
+ const inp = $('chatInput');
+ if (inp) {
+ inp.addEventListener('input', () => autoGrow(inp));
+ inp.addEventListener('mouseup', () => { const h = inp.getBoundingClientRect().height; inp.dataset.dragged = h > 60 ? String(Math.round(h)) : ''; });
+ inp.addEventListener('keydown', e => { if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); chatSend(); } });
+ }
+ on('qaMsgSponsor', 'click', () => { const q = $('qaMsgSponsor'); if (q.dataset.email) openConvo(q.dataset.email, q.dataset.name || 'your sponsor'); });
+ on('lineMsgSponsor', 'click', () => { if (CHAT_SPONSOR) openConvo(CHAT_SPONSOR.email, CHAT_SPONSOR.name || 'your sponsor'); });
+ on('chatAvailToggle', 'change', async () => {
+ const t = $('chatAvailToggle');
+ try { await api('/api/my/chat/available', { available: t.checked }); IAP.status(t.checked ? 'You are available to chat with your line.' : 'Live chat off. People can still leave you a note.', 'ok'); }
+ catch (e) { IAP.status(e.message, 'bad'); t.checked = !t.checked; }
+ });
+ // presence heartbeat + new-message notifier: pop + toast when unread rises
+ setInterval(async () => {
+ try {
+ const r = await (await fetch('/api/my/ping')).json();
+ const n = r.chatUnread || 0;
+ if (n > CHAT_LAST_UNREAD) { playSound('pop'); IAP.status('💬 New message from your team.', 'ok'); }
+ CHAT_LAST_UNREAD = n; setChatBadge(n);
+ } catch (e) {}
+ }, 20000);
+ })();
+
+ // ad surfaces: a banner greets the sign-in screen; members see live
+ // banner + text placements inside the back office (they ARE the audience)
+ IAP.adSlot('banner', 'adSlotLogin');
+ IAP.adSlot('banner', 'adSlotOverview');
+ IAP.adSlot('banner', 'adSlotSide', { width: 125, height: 125 }); // square button ad in the sidebar
+
+ render();
+})();
+
+// ── partner promo codes: typed on the Overview (Marty, 2026-09-12) ──
+(function () {
+ const btn = document.getElementById('promoApply'), inp = document.getElementById('promoCode'), msg = document.getElementById('promoMsg');
+ if (!btn || !inp) return;
+ const say = (t, ok) => { msg.hidden = false; msg.textContent = t; msg.style.color = ok ? 'var(--mint)' : 'var(--bad)'; };
+ const go = async () => {
+ const code = inp.value.trim(); if (!code) { say('Enter a promo code.', false); return; }
+ btn.disabled = true;
+ try {
+ const r = await (await fetch('/api/my/promo/redeem', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ code }) })).json();
+ if (r.error) { say(r.error, false); return; }
+ say('Added ' + Number(r.credits).toLocaleString() + ' credits' + (r.partner ? ' from ' + r.partner : '') + '. They are in your balance now.', true);
+ inp.value = ''; if (typeof loadDashboard === 'function') loadDashboard();
+ } catch (e) { say('Could not apply that code. Try again.', false); }
+ finally { btn.disabled = false; }
+ };
+ btn.addEventListener('click', go); inp.addEventListener('keydown', e => { if (e.key === 'Enter') go(); });
+})();
diff --git a/public/launch.html b/public/launch.html
index 9d59f15..31ebe34 100644
--- a/public/launch.html
+++ b/public/launch.html
@@ -2,8 +2,8 @@
-Founding week checklist | LinkSpin
-
+Launch week checklist | LinkSpin
+
@@ -52,9 +52,10 @@
-
Leaders · founding week
-
Eight things before launch day.
-
Get these done this week, in this order, and your first commissions land in your wallet instead of climbing past you. Everything here reads from your live account.
+
Launch week · Sunday, November 15, 9 AM Central
+
Eight things before Sunday.
+
LinkSpin is open for pre-launch now and opens to the world on Sunday, November 15 at 9 AM Central. Get these done before then, in this order, so your line is set up when everyone else arrives. Everything here reads from your live account.
+
New for launch weekMembers who are in before launch get a Founder badge on their profile (the exact rule is posted before Sunday). And from Sunday, November 15 through Saturday, November 21, the leaderboard runs a launch week contest with POL prizes for the top sponsors. Prize details are announced on launch day.
Members only
Sign in to your member area to open the checklist. Sign in
@@ -75,29 +76,25 @@
The week, day by day
-
Day 1
Items 1 to 3 done in one sitting.
Decide your play, and whether you are going for level 2 or all three.
-
Days 2 to 3
Qualify: two real buyers, or Qualified Start. Leaders: go to five and open level 3.
Line banner uploaded.
-
Days 4 to 6
Place your first two personally.
Walk them through items 1 to 3 on their accounts.
-
Launch day
Everyone releases links at the same time.
Watch the ledger and the Telegram proof feed fill.
+
Today
Items 1 to 3 done in one sitting.
Decide your play, and whether you are going for level 2 or all three.
+
This week
Qualify: two real buyers, or Qualified Start. Leaders: go to five and open level 3.
Line banner uploaded.
+
By Saturday, Nov 14
Place your first two personally.
Walk them through items 1 to 3 on their accounts.
+
Sunday, Nov 15
9 AM Central: everyone shares their link at the same time.
The launch week contest runs through Saturday, Nov 21.
What to send your two this week
-
Text or DM · before launchI'm bringing a small group in early on something before it opens publicly next week. Free to join, real advertising, and every payment lands in your own wallet the second it happens. I want you positioned before the doors open. Set up takes five minutes: your link
-
Text or DM · after they joinThree quick things before launch so your first commission lands with you and not past you: pick your username, link your wallet, switch on payouts. All on the Wallet and Profile tabs. Then send me your two names and we'll get them placed.
+
Text or DM · before launchI'm bringing a small group in early on something before it opens to everyone on Sunday, November 15. Free with an email: one link that rotates every page you promote, a bridge page builder, and an ad slot for your site that pays ad credits. Join before Sunday and you are on my team. Set up takes five minutes: your link
+
Text or DM · after they joinThree quick things before Sunday so your first commission lands with you and not past you: pick your username, link your wallet, switch on payouts. All on the Wallet and Profile tabs. Then send me your two names and we'll get them placed.
-
Launch graphics and posts
-
Two images, no text on them but the headline, so they work anywhere. Post one with the day's line below it; your link and the FOUNDER code are already in each line.
-
- Wide, 1200x630 · for X, Facebook, LinkedIn, link previews Download
- Square, 1080x1080 · for Instagram, Telegram, WhatsApp Download
-
+
Launch posts
+
Ready-to-share posts with your invite link already in them. Copy one and paste it where your people are.
-
Launch week swipes: four emails for your list
-
Send one a day to your own list or contacts, in this order. Your invite link and the FOUNDER code (500 free credits for anyone who joins before Monday 9 AM Central) are already filled in. Copy, paste, send from your own email. Edit anything you like.
+
Launch emails for your list
+
Send from your own email to your own list or contacts. Your invite link is already filled in. Edit anything you like.
-
No income is guaranteed. Results depend on your effort. Crypto carries risk of loss. LinkSpin sells advertising; it is not an investment.
+
Ad credits buy advertising, not income. Payouts come only from purchases in your line. Cryptocurrency involves risk of loss. LinkSpin sells advertising; it is not an investment.