// member share links go out on the share domain (2026-10-20): https://ctbgo.com/ -> /join/ on InstantAdPay. // The domain comes from site config (shareDomain); empty falls back to this site's own /join link. let SHARE_DOMAIN = ''; const SHARE_READY = fetch('/api/config').then(r => r.json()).then(c => { SHARE_DOMAIN = String((c && c.shareDomain) || '').trim(); }).catch(() => {}); function shareLink(ref) { return SHARE_DOMAIN && /^[A-Za-z0-9_]{1,40}$/.test(String(ref)) ? 'https://' + SHARE_DOMAIN + '/' + ref : location.origin + '/join/' + ref; } // 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.$; // dwell timers pause when the tab is away; a focused ad frame or a touch device counts as active (phones never report hasFocus reliably) const tabActive = () => document.visibilityState === 'visible' && (document.hasFocus() || !!(document.activeElement && document.activeElement.tagName === 'IFRAME') || (window.matchMedia && window.matchMedia('(pointer: coarse)').matches)); 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?intent=view')).json(); // display only: never an alert 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) { const e = new Error(r.error); e.data = r; throw e; } // e.data: the full answer (e.g. top-up switch options) return r; } function nextMove(d) { 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 $20 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 $20+ 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 each badge's name ribbon (art differs per tier) { key: 'payouts', label: 'Spark', sub: 'payouts on', img: '/badges/badge-spark.jpg', ribbonY: 0.728 }, { key: 'firstBuyer', label: 'Surge', sub: 'first qualifying buyer', img: '/badges/badge-surge.jpg?v=2', ribbonY: 0.76 }, { key: 'level2', label: 'Circuit', sub: '2 qualifying buyers', img: '/badges/badge-circuit.jpg?v=2', ribbonY: 0.72 }, { key: 'level3', label: 'Nexus', sub: 'fully qualified', img: '/badges/badge-nexus.jpg?v=2', ribbonY: 0.73 }, { key: 'fridays', label: 'Five Fridays', sub: 'five Five Dollar Fridays in a row', img: '/badges/badge-fridays.jpg', ribbonY: 0.719 }, { key: 'gamepass', label: 'Game Pass', sub: 'bought a Game Pass', img: '/badges/badge-gamepass.jpg', ribbonY: 0.84 }, // Monthly Refuel badges (2026-10-24): placeholder gauge art until the final art lands { key: 'refuelStart', label: 'Engine Started', sub: 'first monthly refuel', img: '/badges/badge-refuelstart.jpg', ribbonY: 0.775, earnedOnly: true }, { key: 'refuel3', label: 'Refueled 3 months', sub: 'three monthly refuels in a row', img: '/badges/badge-refuel3.jpg', ribbonY: 0.775, earnedOnly: true }, { key: 'refuel6', label: 'Refueled 6 months', sub: 'six monthly refuels in a row', img: '/badges/badge-refuel6.jpg', ribbonY: 0.775, earnedOnly: true }, { key: 'refuel12', label: 'Refueled 12 months', sub: 'twelve monthly refuels in a row', img: '/badges/badge-refuel12.jpg', ribbonY: 0.775, earnedOnly: true } ]; let lastMilestones = []; function renderBadges(d) { const reached = d.milestonesReached || []; lastMilestones = reached; const strip = $('badgeStrip'); if (!strip) return; $('badgeCard').hidden = false; strip.innerHTML = BADGES.filter(b => !b.earnedOnly || reached.includes(b.key)).map(b => { // earnedOnly: shown once earned (refuel badges) const got = reached.includes(b.key); return '
' + '' + b.label + ' badge' + '
' + 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 > 0 ? ': +' + total + ' bonus credits!' : '! See it in your badges.'), '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'; x.font = 'bold ' + Math.round(c.width * 0.055) + '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 InstantAdPay (' + 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 = ''; document.body.appendChild(back); const close = () => back.remove(); back.addEventListener('click', e => { if (e.target === back) close(); }); back.querySelector('[data-sh="close"]').addEventListener('click', close); back.querySelector('[data-sh="copy"]').addEventListener('click', async () => { try { await navigator.clipboard.writeText(page); IAP.status('Link copied.', 'ok'); } catch (e) { IAP.status('Copy this: ' + page, 'ok'); } }); back.querySelector('[data-sh="save"]').addEventListener('click', () => { const a = document.createElement('a'); a.href = URL.createObjectURL(blob); a.download = 'instantadpay-' + b.label.toLowerCase() + '-badge.jpg'; a.click(); setTimeout(() => URL.revokeObjectURL(a.href), 5000); IAP.status('Your ' + b.label + ' badge is saved.', 'ok'); }); // Massifly has no share intent: copy the post text + link, then open the feed composer (Marty, 2026-09-13) back.querySelector('[data-sh="massifly"]').addEventListener('click', async () => { try { await navigator.clipboard.writeText(text + ' ' + page); IAP.status('Post copied. Paste it into the Massifly composer; the badge preview appears from the link.', 'ok'); } catch (e) { IAP.status('Copy this into Massifly: ' + text + ' ' + page, 'ok'); } window.open('https://massifly.com/account', '_blank', 'noopener'); }); const nat = back.querySelector('[data-sh="native"]'); if (nat) nat.addEventListener('click', async () => { try { const file = new File([blob], 'instantadpay-' + b.label.toLowerCase() + '-badge.jpg', { type: 'image/jpeg' }); if (navigator.canShare && navigator.canShare({ files: [file] })) await navigator.share({ files: [file], title: b.label + ' badge', text: text + ' ' + page }); else await navigator.share({ title: b.label + ' badge', text, url: page }); } catch (e) {} }); } // milestone stepper under "Your next move": lit nodes for what's done, // amber glow on the current target — the same ladder the contract pays function renderSteps(d) { const el = $('ncSteps'); if (!el) return; const b = d.buyerCount || 0; const steps = [ { label: 'Joined', sub: 'free account', hit: true }, { label: 'Spark', sub: 'payouts on', hit: !!d.memberId }, { label: 'Surge', sub: 'first buyer · 50%', hit: b >= 1 }, { label: 'Circuit', sub: '2 buyers · +20%', hit: b >= 2 }, { label: 'Nexus', sub: '5 buyers · +10%', hit: b >= 5 } ]; const cur = steps.findIndex(s => !s.hit); el.innerHTML = steps.map((s, i) => '
' + '' + (s.hit ? '✓' : i + 1) + '' + '' + s.label + '' + s.sub + '
').join(''); } // ── overview v3 charts: hand-rolled SVG/CSS, real data only ── const esc = s => String(s == null ? '' : s).replace(/[&<>"]/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"' }[c])); // Paged lists (Marty, 2026-09-19): 25 rows, then a clearly marked next page, on every list // that grows with the membership. Works on what is already rendered: rows past the page are // hidden and a control bar goes under the list, so a row's buttons and bindings never change. // key remembers the page across re-renders of the same list // host the element the bar is appended to (a wrapper, never a ) // rowSel the rows, queried inside host // opts per (default 25); tail: a selector for a drawer that follows its row and pages // with it; focus: a row predicate, opens on whichever page holds that row const PAGE_SIZE = 25; // My line is the longest page on the dashboard: its lists page at 10 (Marty, 2026-09-26) const LINE_PER = 10; // Sortable + filterable member lists (Marty, 2026-09-29): the holding tank, "Your line" and the three-level // downline share one toolbar. Every row carries joined, last seen, surf earnings and wallet/payout state so a // sponsor can spot "joined days ago, signed in today, earning on their own, wallet linked but payouts off". const LIST_UI = {}; const dayStart = () => { const d = new Date(); d.setHours(0, 0, 0, 0); return d.getTime(); }; const activeToday = m => (m.lastSeen || 0) >= dayStart(); const LIST_SORTS = [ { k: 'seen', label: 'Last seen', v: m => m.lastSeen || 0 }, { k: 'joined', label: 'Joined', v: m => m.joined || 0 }, { k: 'earned', label: 'Surf earnings', v: m => m.earned || 0 }, { k: 'balance', label: 'Earned balance', v: m => m.balance || 0 }, { k: 'name', label: 'Name', v: m => String(m.name || '').toLowerCase(), str: true }, ]; const LIST_FILTERS = [ { k: 'today', label: 'Active today', t: m => activeToday(m) }, { k: 'earning', label: 'Earning', t: m => (m.earned || 0) > 0 }, { k: 'wallet', label: 'Wallet linked', t: m => !!m.wallet }, { k: 'nopay', label: 'Wallet, payouts off', t: m => !!m.wallet && !m.activated }, { k: 'payouts', label: 'Payouts on', t: m => !!m.activated }, { k: 'nowallet', label: 'No wallet', t: m => !m.wallet }, ]; const listState = key => LIST_UI[key] || (LIST_UI[key] = { sort: 'seen', dir: -1, on: new Set() }); function listApply(key, rows) { const st = listState(key); const s = LIST_SORTS.find(x => x.k === st.sort) || LIST_SORTS[0]; const out = (rows || []).filter(m => m.own || [...st.on].every(k => { const f = LIST_FILTERS.find(x => x.k === k); return !f || f.t(m); })); out.sort((a, b) => { const x = s.v(a), y = s.v(b); return (s.str ? String(x).localeCompare(String(y)) : x - y) * st.dir; }); return out; } function listBar(key, total, shown, rerender, opts) { const st = listState(key); const hide = (opts && opts.hide) || []; const bar = document.createElement('div'); bar.className = 'lst-bar'; bar.innerHTML = '' + '' + '' + LIST_FILTERS.filter(f => !hide.includes(f.k)).map(f => '').join('') + '' + '' + (shown === total ? total + (total === 1 ? ' person' : ' people') : shown + ' of ' + total) + ''; bar.querySelector('select').addEventListener('change', e => { st.sort = e.target.value; st.dir = st.sort === 'name' ? 1 : -1; rerender(); }); bar.querySelector('.lst-dir').addEventListener('click', () => { st.dir = -st.dir; rerender(); }); bar.querySelectorAll('[data-f]').forEach(b => b.addEventListener('click', () => { const k = b.dataset.f; if (st.on.has(k)) st.on.delete(k); else st.on.add(k); rerender(); })); return bar; } const seenAgo = t => { if (!t) return 'never'; const d = Date.now() - t; if (d < 3600e3) return Math.max(1, Math.round(d / 60e3)) + ' min ago'; if (d < 86400e3) return Math.round(d / 3600e3) + 'h ago'; const days = Math.floor(d / 86400e3); return days === 1 ? 'yesterday' : days + ' days ago'; }; const seenChip = m => m.lastSeen ? '' + (activeToday(m) ? 'active today' : 'seen ' + seenAgo(m.lastSeen)) + '' : 'never signed in'; const earnChip = m => '' + (m.earned || 0).toLocaleString() + ' cr earned'; const walletChip = m => m.activated ? 'wallet · payouts on' : m.wallet ? 'wallet · payouts off' : 'no wallet'; const memberChips = m => seenChip(m) + ' ' + earnChip(m) + ' ' + walletChip(m); // Section pills at the top of My line: one per visible card marked data-jump, the one in view lit up. // Cards that show or hide themselves (sponsor, upline messages) rebuild the row when they change. let lineJumpObs = null; function buildLineJump() { const nav = document.getElementById('lineJump'); const pane = document.getElementById('pane-line'); if (!nav || !pane) return; const cards = [...pane.querySelectorAll(':scope > .card[data-jump]')].filter(c => !c.hidden); nav.innerHTML = cards.map(c => '').join(''); nav.hidden = cards.length < 2; const top = document.querySelector('.bo-top'); nav.style.setProperty('--jumpTop', (top ? top.offsetHeight : 0) + 'px'); pane.style.setProperty('--jumpTop', (top ? top.offsetHeight : 0) + 'px'); nav.querySelectorAll('[data-jumpto]').forEach(b => b.addEventListener('click', () => { const c = document.getElementById(b.dataset.jumpto); if (!c) return; c.scrollIntoView({ behavior: 'smooth', block: 'start' }); nav.querySelectorAll('.chip-t').forEach(x => x.classList.toggle('on', x === b)); })); if (lineJumpObs) lineJumpObs.disconnect(); if ('IntersectionObserver' in window) { const seen = new Map(); lineJumpObs = new IntersectionObserver(ents => { for (const e of ents) seen.set(e.target.id, e.isIntersecting ? e.boundingClientRect.top : null); let best = null; for (const [id, t] of seen) if (t != null && (best == null || t < seen.get(best))) best = id; if (best) { nav.querySelectorAll('.chip-t').forEach(x => x.classList.toggle('on', x.dataset.jumpto === best)); const on = nav.querySelector('.chip-t.on'); if (on && nav.scrollWidth > nav.clientWidth) nav.scrollLeft = on.offsetLeft - 16; } }, { rootMargin: '-120px 0px -55% 0px' }); cards.forEach(c => lineJumpObs.observe(c)); } } { const pane = document.getElementById('pane-line'); if (pane && 'MutationObserver' in window) new MutationObserver(() => buildLineJump()).observe(pane, { subtree: false, childList: false, attributes: true, attributeFilter: ['hidden'] }); if (pane) pane.querySelectorAll(':scope > .card[data-jump]').forEach(c => { if ('MutationObserver' in window) new MutationObserver(() => buildLineJump()).observe(c, { attributes: true, attributeFilter: ['hidden'] }); }); } const PAGE_AT = {}; function pageList(key, host, rowSel, opts) { if (!host) return; opts = opts || {}; const per = opts.per || PAGE_SIZE; const rows = [...host.querySelectorAll(rowSel)]; const old = host.querySelector(':scope > .pgr'); if (old) old.remove(); if (rows.length <= per) { rows.forEach(r => { r.hidden = false; }); return; } const pages = Math.ceil(rows.length / per); let p = PAGE_AT[key] || 1; if (opts.focus) { const i = rows.findIndex(opts.focus); if (i >= 0) p = Math.floor(i / per) + 1; } p = Math.min(Math.max(1, p), pages); PAGE_AT[key] = p; const start = (p - 1) * per; rows.forEach((r, i) => { const on = i >= start && i < start + per; r.hidden = !on; if (opts.tail) { const t = r.nextElementSibling; if (t && t.matches(opts.tail) && !on && !t.hidden) { t.hidden = true; const b = r.querySelector('[aria-expanded]'); if (b) { b.setAttribute('aria-expanded', 'false'); b.textContent = 'Activity \u25BE'; } } } }); const bar = document.createElement('div'); bar.className = 'pgr'; bar.innerHTML = 'Showing ' + (start + 1) + '\u2013' + Math.min(start + per, rows.length) + ' of ' + rows.length + '' + '' + 'Page ' + p + ' of ' + pages + '' + ''; bar.querySelectorAll('[data-go]').forEach(b => b.addEventListener('click', () => { PAGE_AT[key] = Number(b.dataset.go); pageList(key, host, rowSel, Object.assign({}, opts, { focus: null })); host.scrollIntoView({ behavior: 'smooth', block: 'start' }); })); host.appendChild(bar); } const CH = { mint: '#43e8c3', cyan: '#54ccff', violet: '#9d7dff', amber: '#ffb238', track: 'rgba(139,166,156,.18)' }; 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' + (d.earnedReserved ? ' (+' + d.earnedReserved.toLocaleString() + ' earned and bonus credits working in your live campaigns)' : '') + (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' ? (e.override ? 'L4' : '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('' + esc(it.docLabel || 'Open material') + ''); return head + '

' + esc(it.title || 'Lesson') + '

' + (it.desc ? '

' + esc(it.desc) + '

' : '') + (media ? '

' + media + '

' : '') + (links.length ? '

' + links.join(' ') + '

' : '') + '
'; }).join(''); } catch (e) {} } // visual line tree on the Overview: YOU + three levels, qualified directs in gold function renderRoster(wrap, all) { const rows = listApply('roster', all); wrap.querySelectorAll(':scope > .lst-bar, :scope > table, :scope > .pgr, :scope > .lst-none').forEach(n => n.remove()); wrap.appendChild(listBar('roster', all.length, rows.length, () => renderRoster(wrap, all))); if (!rows.length) { wrap.insertAdjacentHTML('beforeend', '

Nobody in your line matches those filters.

'); return; } const t = document.createElement('table'); t.className = 'roster'; t.innerHTML = rows.map(r => '' + '' + '' + '').join(''); wrap.appendChild(t); pageList('roster', wrap, 'table.roster tr', { per: LINE_PER }); } 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 $20+ 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); // click a chip to drill down: My line opens with that person's Activity panel expanded (Marty, 2026-09-15) const go = ref => { LINE_FOCUS_REF = ref; setPane('line'); }; el.querySelectorAll('[data-goref]').forEach(n => { n.addEventListener('click', () => go(n.dataset.goref)); n.addEventListener('keydown', e => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); go(n.dataset.goref); } }); }); } catch (e) {} } let LINE_FOCUS_REF = null; // set by an Overview chip click; consumed once My line has rendered // "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 => '

' + (n.date > seen ? '● ' : '') + '' + esc(n.title) + ' ' + esc(n.date) + '

').join(''); const rm = r.roadmap.filter(x => x.status === 'building').slice(0, 2).map(x => '

Building: ' + esc(x.title) + (x.eta ? ' (' + esc(x.eta) + ')' : '') + '

').join(''); $('newsList').innerHTML = notes + rm + '

All release notes and the roadmap →

'; $('newsCard').hidden = false; $('newsCard').addEventListener('click', () => { try { localStorage.setItem('iap.news.seen', r.latest || ''); } catch (e) {} $('newsList').querySelectorAll('span[style*="mint"]').forEach(s => { if (s.textContent === '●') s.remove(); }); }, { once: true }); } catch (e) {} } // Leaderboard card: top 5 this week + your own rank + the prize (Marty, 2026-09-14) async function loadLeaderboard() { if (!$('lbCard')) return; try { const r = await (await fetch('/api/leaderboard?period=week')).json(); const esc = t => String(t == null ? '' : t).replace(/[&<>"]/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"' }[c])); let h = r.prize ? '

Prize this week: ' + esc(r.prize) + '

' : ''; h += r.top.length ? '
' + esc(r.name || r.email || '') + 'joined ' + new Date(r.joined).toLocaleDateString() + '' + memberChips(r) + '' + esc(r.status) + '
' + r.top.slice(0, 5).map(x => '').join('') + '
' + x.rank + '' + esc(x.name) + '' + x.sales + ' sold · $' + x.usd + '
' : '

No packages sold yet this week. First sale takes the top spot.

'; h += r.me ? '

You: #' + r.me.rank + ' · ' + r.me.sales + ' sold · $' + r.me.usd + '

' : '

You: no sales yet this week. Sales are $20+ packages bought by people you sponsor.

'; h += '

Full leaderboard: week, month, all time →

'; $('lbList').innerHTML = h; $('lbCard').hidden = false; } catch (e) {} } // Getting-started stepper: username -> wallet -> payouts -> first package. The current step gets one big // button that opens the right tab and pulses the control (Jim: "it wasn't obvious", 2026-09-14) function renderSteps(d) { const card = $('gsCard'); if (!card) return; const hasUser = !!d.username, hasWallet = !!d.address, hasPayouts = !!d.memberId, hasPackage = !!(d.memberId && (d.credits || 0) > 0); const steps = [ { k: 'user', t: 'Pick a username', done: hasUser }, { k: 'wallet', t: 'Link your wallet', done: hasWallet }, { k: 'payouts', t: 'Switch on payouts', done: hasPayouts }, { k: 'package', t: 'Your first package', done: hasPackage } ]; if (steps.every(x => x.done)) { card.hidden = true; return; } const cur = steps.find(x => !x.done); let collapsed = false; try { collapsed = localStorage.getItem('iap.gs.collapsed') === '1'; } catch (e) {} $('gsSub').innerHTML = steps.filter(x => x.done).length + ' of 4 done · ' + (collapsed ? 'show' : 'hide') + ''; $('gsToggle').addEventListener('click', e => { e.preventDefault(); try { localStorage.setItem('iap.gs.collapsed', collapsed ? '0' : '1'); } catch (er) {} renderSteps(d); }); $('gsSteps').hidden = collapsed; $('gsNow').hidden = collapsed; $('gsSteps').innerHTML = steps.map((x, i) => '
' + (x.done ? '✓' : i + 1) + '' + x.t + '
').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 $5. The $20 Activation 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]; $('gsNow').innerHTML = '

Next: ' + copy[0] + '' + copy[1] + (cur.k === 'wallet' ? ' Wallet guide' : '') + '

'; $('gsGo').addEventListener('click', copy[3]); card.hidden = false; } // member welcome offer from the games (2026-10-05): a game's after-win card sends players to /my?from=#buy. // We remember the game (through sign-in), tell the server once, and show the offer + the way back to the perk. try { const fm = /[?&]from=([a-z]{3,20})/.exec(location.search); if (fm) { sessionStorage.setItem('iap.starterFrom', fm[1]); history.replaceState(null, '', '/my' + (location.hash || '')); } } catch (e) {} async function starterBanner(me) { let from = null; try { from = sessionStorage.getItem('iap.starterFrom'); } catch (e) {} let v = null; if (from) { try { sessionStorage.removeItem('iap.starterFrom'); } catch (e) {} v = await (await fetch('/api/starter', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ game: from }) })).json(); } else v = await (await fetch('/api/starter')).json(); if (!v || !v.on || !v.game) return; const pane = document.querySelector('#pane-buy .card'); if (!pane) return; let box = document.getElementById('starterBox'); if (!box) { box = document.createElement('div'); box.id = 'starterBox'; pane.insertBefore(box, pane.children[1] || null); } const esc = t => String(t).replace(/[&<>"]/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"' }[c])); box.style.cssText = 'border:1px solid var(--gold, #e2b04a);border-radius:12px;padding:12px 14px;margin:0 0 14px;background:rgba(226,176,74,.08)'; box.innerHTML = v.eligible ? 'Welcome from ' + esc(v.game) + '!
Your first package, $5 or more, comes with +' + v.bonus + ' bonus ad credits, and ' + esc(v.perk) + ' waiting for you in ' + esc(v.game) + '.' : 'You are a member. ' + (v.granted ? 'Your +' + v.bonus + ' welcome credits are in your balance. ' : '') + 'Your ' + esc(v.perk) + ' is waiting in ' + esc(v.game) + '.
Back to ' + esc(v.game) + ' to collect it'; if (from && !/^#(passes|games)/.test(location.hash)) setPane('buy'); // a game's Buy-a-pass link (#passes) stays on the pass card } function jumpTo(pane, id) { setPane(pane); setTimeout(() => { const el = id && $(id); if (!el) return; el.scrollIntoView({ behavior: 'smooth', block: 'center' }); el.classList.remove('pulse'); void el.offsetWidth; el.classList.add('pulse'); try { el.focus({ preventScroll: true }); } catch (e) {} }, 250); } async function loadDashboard() { try { loadNews(); loadLeaderboard(); const d = await (await fetch('/api/my/dashboard')).json(); if (d.error) return; chatSync(d); try { renderSteps(d); } catch (e) {} MYID = d.memberId || MYID; startLiveFeed(); if (!window.__lbChecked) { // daily login bonus, once per session (server guards once/day) window.__lbChecked = true; api('/api/my/login-bonus').then(r => { if (r && r.comeback > 0) { IAP.status('🎉 Welcome back! +' + r.comeback + ' bonus credits for coming back, plus +' + r.granted + ' for signing in today.', 'ok'); playSound('chaching'); setTimeout(loadDashboard, 900); } else if (r && r.granted > 0) { IAP.status('🎁 Daily login bonus: +' + r.granted + ' credits' + (r.streak > 1 ? ' · ' + r.streak + '-day streak' : '') + '!', 'ok'); playSound('chaching'); setTimeout(loadDashboard, 900); } }).catch(() => {}); } const earnedAv = d.earnedCredits || 0, inCamp = d.inCampaigns || 0; $('dbCredits').textContent = ((d.credits || 0) + earnedAv).toLocaleString(); $('dbCreditsSub').textContent = (d.credits || 0).toLocaleString() + ' purchased' + (d.creditedCredits ? ' (' + d.creditedCredits.toLocaleString() + ' credited to you)' : '') + ' · ' + earnedAv.toLocaleString() + ' earned' + (inCamp ? ' · ' + inCamp.toLocaleString() + ' in campaigns' : ''); $('dbEarned').textContent = IAP.fmtPol(d.earnedWei || '0'); usdRate().then(r => { const el = $('dbEarnedUsd'); if (el) el.textContent = r.usd > 0 && d.earnedWei && d.earnedWei !== '0' ? usdOf(d.earnedWei, r) + ' today' : ''; }); $('dbBuyers').textContent = d.buyerCount || 0; if (d.buyerCountPositions) { const sub = $('dbBuyersSub'); if (sub) sub.textContent = '+' + d.buyerCountPositions + ' on your linked positions (count toward badges; levels pay on your main position)'; } $('dbTeam').textContent = (d.referrals || []).length; // trend chips: only real, computable facts const ec = $('dbEarnedChip'); if (ec && d.earnCount) { ec.hidden = false; ec.textContent = d.earnCount + ' instant payout' + (d.earnCount > 1 ? 's' : ''); } const bc = $('dbBuyersChip'); if (bc && d.memberId) { bc.hidden = false; bc.textContent = (d.buyerCount || 0) >= 5 ? 'level 3 open' : (d.buyerCount || 0) >= 2 ? 'level 2 open' : 'level 2 at 2 buyers'; } const tc = $('dbTeamChip'), wk = (d.referrals || []).filter(r => Date.now() - new Date(r.joined) < 6048e5).length; if (tc && wk) { tc.hidden = false; tc.textContent = '+' + wk + ' this week'; } setInboxBadge(d.inboxUnread || 0); if (d.sponsorMsg) showSponsorModal(d.sponsorMsg); renderBadges(d); loadFeatured(); loadLineTree(d.buyerCount || 0); loadCharts(d); $('nextMove').textContent = nextMove(d); renderSteps(d); const wrap = $('rosterWrap'); if ((d.referrals || []).length) { $('rosterEmpty').hidden = true; renderRoster(wrap, d.referrals); } // 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 await SHARE_READY; const link = shareLink(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 $20 package first).'); } } catch (e) {} // Share the presentation (2026-10-15): instantadpay.com/presentation?ref= sets the same sponsor cookie as /join { const tokP = d.username || d.refCode || d.memberId; const ps = $('promoPresStrip'); if (ps && tokP) { const pl = 'https://instantadpay.com/presentation?ref=' + encodeURIComponent(tokP); ps.hidden = false; $('promoPresLink').textContent = pl; $('promoPresOpen').href = '/presentation?ref=' + encodeURIComponent(tokP); $('promoPresCopy').onclick = async () => { try { await navigator.clipboard.writeText(pl); IAP.status('Presentation link copied.', 'ok'); } catch (e) { IAP.status('Copy failed. Select the link and copy it.', 'bad'); } }; } } 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', 'buy', 'campaigns', 'earn', 'earnings', 'promo', 'training', 'help', 'games', 'wallet', 'profile', 'engine']; // engine: the Engine Room (fuel.js, 2026-10-24) const TITLES = { engine: 'Engine Room', overview: 'Overview', line: 'My line', pipeline: 'Pipeline', buy: 'Buy packages', campaigns: 'Campaigns', earn: 'Earn credits', earnings: 'Earnings', promo: 'Promo tools', training: 'Training', help: 'Help and support', games: 'Games', wallet: 'Wallet & account', profile: 'Profile' }; function setPane(name) { let paneQ = String(name || '').split('?')[1] || ''; name = String(name || '').split('?')[0]; // /my#games?pass=1 opens the Game Pass card (deep link from the games) if (name === 'passes') { name = 'games'; paneQ = 'pass=1'; } // /my#passes: the Shards of Valor Buy button (2026-10-18), same card 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]; // 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); loadPdCard(); } // refresh whichever sub-tab is active; PassiveDrip card (2026-10-01) else if (vidState.token) stopVideo(); if (name === 'profile') loadLineBanner(); if (name === 'line') { buildLineJump(); 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') { if (/(^|&)g=leader/.test(paneQ)) loadTraining.filter = 'Leader tools'; loadTraining(); } if (name === 'pipeline') loadPipeline(); if (name === 'games') loadGames(paneQ); if (name === 'help' && window.IAPSupport) IAPSupport.help(paneQ); // help desk tickets (2026-10-16) document.getElementById('memberArea').classList.remove('side-open'); // close mobile drawer const keepQ = name === 'help' && paneQ ? '?' + paneQ : ''; // Help keeps ?t= so a reload reopens the ticket if (location.hash !== '#' + name + keepQ) history.replaceState(null, '', '#' + name + keepQ); } 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; $('authArea').hidden = !!signedIn; $('memberArea').hidden = !signedIn; if ($('mcFinish')) $('mcFinish').hidden = !walletOnly; if (!signedIn) return; if ($('adminLink')) $('adminLink').hidden = !me.isAdmin; // admin portal link, only for ADMIN_EMAIL if (!render.gamesChecked) { render.gamesChecked = true; fetch('/api/my/games').then(r => r.json()).then(g => { if ($('gamesNav')) $('gamesNav').hidden = !(g.games && g.games.length); }).catch(() => {}); } // Games appears once any game is live (admin sees previews) // 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; } // came from a Drip Runner share link: once they have a username, straight back into the game (2026-09-30) if (me.returnTo === 'driprunner' && !render.toGame) { render.toGame = true; location.href = '/api/my/driprunner'; return; } if (me.returnTo === 'gemkingdom' && !render.toGame) { render.toGame = true; location.href = '/api/my/gemkingdom'; return; } // Gem Kingdom sent them here to sign in (2026-10-01) if (me.returnTo === 'gkshop' && !render.toGame) { render.toGame = true; location.href = '/gk/shop/resume'; return; } if (me.returnTo === 'spookydoors' && !render.toGame) { render.toGame = true; location.href = '/api/my/spookydoors'; return; } // Spooky Doors sent them here to sign in (2026-10-02) if (me.returnTo === 'polybreak' && !render.toGame) { render.toGame = true; location.href = '/api/my/polybreak'; return; } // PolyBreak sent them here to sign in (2026-10-13) if (me.returnTo === 'shardsofvalor' && !render.toGame) { render.toGame = true; location.href = '/api/my/shardsofvalor'; return; } // Shards of Valor sent them here to sign in (2026-10-18) if (me.returnTo === 'pwmint' && !render.toGame) { render.toGame = true; location.href = '/pw/mint/resume'; return; } // PolyWarriors paid mint (2026-10-05) if (me.pwMint && !me.gkShop && !me.sdShop && !document.getElementById('pwBack')) { const d = document.createElement('a'); d.id = 'pwBack'; document.body.classList.add('hasback'); d.href = '/pw/mint/resume'; d.textContent = 'PolyWarriors mint: buy a package and you go straight back to the game when it settles. Or go back now →'; d.setAttribute('style', 'position:fixed;left:12px;right:12px;bottom:14px;z-index:9999;display:block;padding:14px 44px 14px 16px;border-radius:14px;background:linear-gradient(180deg,#22E5FF,#7A2CFF);color:#fff;font-weight:800;text-align:center;text-decoration:none;box-shadow:0 10px 30px rgba(0,0,0,.45)'); document.body.appendChild(d); // x = not now: clears the bar cookie (the waiting mint order stays and a later package still completes it), Marty 2026-10-11 const x = document.createElement('button'); x.type = 'button'; x.setAttribute('aria-label', 'Hide'); x.textContent = '×'; x.setAttribute('style', 'position:absolute;right:8px;top:50%;transform:translateY(-50%);width:30px;height:30px;border:0;border-radius:50%;background:rgba(0,0,0,.28);color:#fff;font-size:20px;line-height:30px;cursor:pointer;padding:0'); x.addEventListener('click', ev => { ev.preventDefault(); ev.stopPropagation(); fetch('/pw/mint/dismiss', { method: 'POST' }).catch(() => {}); d.remove(); document.body.classList.remove('hasback'); if (me) me.pwMint = false; }); d.appendChild(x); } if (me.returnTo === 'sdshop' && !render.toGame) { render.toGame = true; location.href = '/sd/shop/resume'; return; } if (me.sdShop && !document.getElementById('sdBack')) { const d = document.createElement('a'); d.id = 'sdBack'; document.body.classList.add('hasback'); d.href = '/sd/shop/resume'; d.textContent = 'Finish your Spooky Doors costume order \u2192'; d.setAttribute('style', 'position:fixed;left:12px;right:12px;bottom:' + (me.gkShop ? '74px' : '14px') + ';z-index:9999;display:block;padding:14px 16px;border-radius:14px;background:#FF8A1F;color:#2a1200;font-weight:800;text-align:center;text-decoration:none;box-shadow:0 5px 0 #C25A06,0 10px 30px rgba(0,0,0,.45)'); document.body.appendChild(d); } if (me.gkShop && !document.getElementById('gkBack')) { const d = document.createElement('a'); d.id = 'gkBack'; document.body.classList.add('hasback'); d.href = '/gk/shop/resume'; d.textContent = 'Finish your Gem Kingdom Crowns order \u2192'; d.setAttribute('style', 'position:fixed;left:12px;right:12px;bottom:14px;z-index:9999;display:block;padding:14px 16px;border-radius:14px;background:linear-gradient(180deg,#E8455A,#A8172B);color:#fff;font-weight:800;text-align:center;text-decoration:none;box-shadow:0 10px 30px rgba(0,0,0,.45)'); document.body.appendChild(d); } if (me.returnTo === 'passivedrip' && !render.toGame) { render.toGame = true; location.href = '/api/my/passivedrip'; return; } // PassiveDrip sent them here to sign in (2026-10-01) // 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, '', '/my' + (location.hash || '')); (async () => { try { if (!(await showGauntlet())) await showLoginAd(); } catch (e) {} await render(); })(); } starterBanner(me).catch(() => {}); 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(); if (window.IAPSupport) IAPSupport.badge(); // Help badge: Marty replied to a ticket 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) 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); $('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) { await SHARE_READY; $('inviteLine').textContent = shareLink(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 $20+ 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.'; } } // Dollar value at today's POL price (Marty, 2026-10-22): one cached rate from our own server (5 min there, 2 min here), // shown as "≈ $x.xx" next to POL amounts on the member's own pages. It is today's value, not the value on the payout day. let USD = null; async function usdRate() { if (USD && Date.now() - USD.got < 120000) return USD; try { const r = await (await fetch('/api/public/polusd')).json(); USD = { usd: Number(r.usd) || 0, at: Number(r.at) || Date.now(), got: Date.now() }; } catch (e) { USD = USD || { usd: 0, at: 0, got: Date.now() }; } return USD; } function usdOf(wei, r) { let pol = 0; try { pol = Number(BigInt(wei || '0') / 10n ** 12n) / 1e6; } catch (e) {} const v = pol * ((r && r.usd) || 0); return '≈ $' + v.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 }); } function usdNote(r) { if (!r || !(r.usd > 0)) return ''; const mins = Math.max(0, Math.round((Date.now() - r.at) / 60000)); return '1 POL ≈ $' + r.usd.toLocaleString('en-US', { minimumFractionDigits: 4, maximumFractionDigits: 4 }) + ' at today’s price (updated ' + (mins < 1 ? 'just now' : mins + ' min ago') + '). Dollar amounts are what the POL is worth today, not on the day it was paid.'; } 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.'); usdRate().then(r => { const note = $('earnUsdNote'); if (note) note.textContent = usdNote(r); if (!(r.usd > 0)) return; const rows = $('earnFeed').querySelectorAll('.row'); let i = 0; for (const ev of (a.earnings || [])) { const row = rows[i++]; if (!row || !ev.amountWei) continue; const s = document.createElement('span'); s.className = 'usd muted small'; s.textContent = usdOf(ev.amountWei, r); const tx = row.querySelector('.tx'); row.insertBefore(s, tx || null); } }); fill('refFeed', a.referrals, 'No referral activity yet. Share your invite link.'); fill('buyFeed', a.purchases, 'No purchases from your wallet yet.'); } catch (e) {} initTrace(); } // payment trace (2026-09-16): who was paid, who was skipped and why, per purchase let traceInit = false; function initTrace() { if (traceInit || !$('trGo')) return; traceInit = true; const run = async () => { const who = ($('trWho').value || '').trim(); const out = $('trOut'); const msg = $('trMsg'); msg.textContent = 'Reading the chain…'; out.innerHTML = ''; try { const c = await IAP.getConfig(); const r = await (await fetch('/api/my/trace?who=' + encodeURIComponent(who))).json(); if (r.error) { msg.textContent = r.error; return; } msg.textContent = ''; const nm = id => id ? ('#' + id + (r.names[id] ? ' @' + esc(r.names[id]) : '')) : 'nobody'; const pol = w => IAP.fmtPol(w) + ' POL'; const when = ts => new Date(ts).toLocaleString([], { month: 'short', day: 'numeric', hour: 'numeric', minute: '2-digit' }); let h = '

' + nm(r.memberId) + ' · ' + (r.activated ? 'activated under ' + nm(r.sponsorId) : 'not activated on the chain yet') + ' · ' + r.buyersNow + ' qualifying buyer' + (r.buyersNow === 1 ? '' : 's') + ' (level 2 needs 2, level 3 needs 5)

'; if (!r.purchases.length) { out.innerHTML = h + '

No purchases involving ' + nm(r.memberId) + ' yet.

'; return; } for (const p of r.purchases) { const isBuyer = p.buyerId === r.memberId; h += '
' + '
' + when(p.ts) + ' · ' + nm(p.buyerId) + ' bought a $' + (p.priceCents / 100).toFixed(0) + ' package (' + pol(p.paidWei) + ')' + (p.sponsorId ? ' · sponsor ' + nm(p.sponsorId) : '') + (c.explorer ? ' · verify ↗' : '') + '
'; for (const t of p.tiers) { const me = t.paidTo === r.memberId, skippedMe = t.skipped.some(x => x.id === r.memberId); let line = 'Level ' + t.tier + ' (' + t.pct + '%): '; for (const x of t.skipped) line += '' + nm(x.id) + ' skipped (' + (x.reason === 'unqualified' ? 'not qualified: had ' + x.buyersThen + ' of ' + (t.tier === 2 ? 2 : 5) + ' qualifying buyers then' : esc(x.reason)) + ') → '; line += t.paidTo ? '' + nm(t.paidTo) + ' paid ' + pol(t.amountWei) + '' : 'no eligible catcher within reach → company'; h += '
' + line + '
'; } h += '
Platform (20%): ' + pol(p.adminWei) + (isBuyer ? '' : '') + '
'; } h += '

A skipped level means that person had not unlocked it when the purchase settled. Qualification never applies backwards; the next purchase after they qualify pays them.

'; out.innerHTML = h; } catch (e) { msg.textContent = 'Could not read the chain just now. Try again in a minute.'; } }; $('trGo').addEventListener('click', run); $('trWho').addEventListener('keydown', e => { if (e.key === 'Enter') { e.preventDefault(); run(); } }); } // credit activity ledger under the campaign table (2026-09-16): every earn and spend with its reason // Archived campaigns: everything they did, none of the clutter and none of the reservation. function renderArchived(el, r) { const rows = r.archived || []; if (!rows.length) return; const box = document.createElement('div'); box.className = 'card'; box.style.marginTop = '18px'; // what each one gave back = budget not delivered (flat packs are charged in full when bought, so theirs is 0) const leftOf = c => Math.max(0, Number(c.budget || 0) - Number(c.spent || 0) - Number(c.accrued || 0)); const returned = rows.reduce((n, c) => n + leftOf(c), 0); box.innerHTML = '

Archived

' + rows.length + ' finished campaign' + (rows.length === 1 ? '' : 's') + ' · ' + returned.toLocaleString() + ' unspent credit' + (returned === 1 ? '' : 's') + ' returned
' + '
' + rows.map(c => '' + '' + '' + '' + '' + '' + '').join('') + '
NameTypeViews hereClicksSpentReturnedRan until
' + esc(c.name || ('#' + c.id)) + '' + esc(c.type) + '' + Number(c.imps || 0).toLocaleString() + '' + Number(c.clicks || 0).toLocaleString() + '' + Number(c.spent || 0).toLocaleString() + '' + leftOf(c).toLocaleString() + '' + (c.created ? new Date(c.created).toLocaleDateString() : '') + '
' + '

Archived campaigns keep every number they earned. They serve nothing and reserve nothing, so any budget they had not delivered is back in your Available balance (the Returned column). A campaign that delivered its whole budget has nothing left to return, and visit packs, Golden Door, login and featured runs are paid in full when bought. Restore brings one back, paused.

'; el.appendChild(box); box.querySelectorAll('[data-unarch]').forEach(b => b.addEventListener('click', async () => { b.disabled = true; try { await api('/api/my/campaigns/' + b.dataset.unarch + '/unarchive'); IAP.status('Restored, and paused. Press Resume when you want it running.', 'ok'); await loadCampaigns(); loadDashboard(); } catch (e) { IAP.status(e.message, 'bad'); b.disabled = false; } })); } async function loadCreditActivity(el) { try { const r = await (await fetch('/api/my/credits/activity')).json(); if (!r.items || !r.items.length) return; const box = document.createElement('div'); box.id = 'creditActivity'; box.style.marginTop = '16px'; const when = ts => new Date(ts).toLocaleString([], { month: 'short', day: 'numeric', hour: 'numeric', minute: '2-digit' }); box.innerHTML = '

Credit activity

' + '

Every credit that came in or went out, newest first. Earned credits are spent before purchased ones, so an earn followed by a buy shows as two lines here. Views a campaign delivers roll up into one line per day.

' + '
' + r.items.map(i => '').join('') + '
' + when(i.ts) + '' + (i.delta > 0 ? '+' : '') + i.delta.toLocaleString() + '' + esc(i.note) + '
'; el.appendChild(box); pageList('credits', box, 'tbody tr'); } catch (e) {} } // Campaigns > Conversion tracking (2026-10-23). Goals and counts come from LinkSpin through /api/my/conversions. Anything // going wrong here only changes this card's own text: the campaign list never depends on it. let convSel = null, convCamps = []; const convFmt = n => Number(n || 0).toLocaleString(undefined, { maximumFractionDigits: 1 }); function convSnips(host, g) { const h = 'https://' + String(host || 'linkspin.app').replace(/^https?:\/\//, '').replace(/\/+$/, ''); const px = encodeURIComponent(g.px), goal = encodeURIComponent(g.name); const val = g.value != null && g.value !== '' ? '&value=' + encodeURIComponent(g.value) : ''; return { landing: '