// 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;
}
} 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;
}
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.';
}
// achievement badges: the milestone ladder as unlockable medals + share-to-image
const BADGES = [
{ key: 'payouts', label: 'Payouts On', sub: 'wallet linked', icon: '' },
{ key: 'firstBuyer', label: 'First Buyer', sub: 'first qualified referral', icon: '' },
{ key: 'level2', label: 'Level 2', sub: '2 qualifying buyers', icon: '' },
{ key: 'level3', label: 'Level 3', sub: 'fully qualified', icon: '' }
];
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 ? '' : '') + '
';
}).join('');
strip.querySelectorAll('[data-badge]').forEach(btn =>
btn.addEventListener('click', () => shareBadge(btn.dataset.badge, d)));
// celebrate anything newly granted this load
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');
}
}
// compose a shareable badge image on a canvas (zero-dep) and download it
function shareBadge(key, d) {
const b = BADGES.find(x => x.key === key); if (!b) return;
const c = document.createElement('canvas'); c.width = 1200; c.height = 630;
const x = c.getContext('2d');
const g = x.createLinearGradient(0, 0, 1200, 630);
g.addColorStop(0, '#041109'); g.addColorStop(1, '#0b2018');
x.fillStyle = g; x.fillRect(0, 0, 1200, 630);
x.strokeStyle = 'rgba(67,232,195,.5)'; x.lineWidth = 6; x.strokeRect(24, 24, 1152, 582);
x.fillStyle = '#43e8c3'; x.font = 'bold 34px Sora, sans-serif'; x.fillText('InstantAdPay', 70, 100);
x.fillStyle = '#8ba69c'; x.font = '22px Sora, sans-serif'; x.fillText('ACHIEVEMENT UNLOCKED', 70, 150);
// medal circle
x.beginPath(); x.arc(600, 320, 110, 0, Math.PI * 2);
const mg = x.createRadialGradient(600, 290, 20, 600, 320, 110);
mg.addColorStop(0, 'rgba(67,232,195,.45)'); mg.addColorStop(1, 'rgba(9,26,19,.9)');
x.fillStyle = mg; x.fill(); x.strokeStyle = '#43e8c3'; x.lineWidth = 5; x.stroke();
x.fillStyle = '#eef7f3'; x.textAlign = 'center';
x.font = 'bold 64px Sora, sans-serif'; x.fillText(b.label, 600, 500);
x.font = '26px Sora, sans-serif'; x.fillStyle = '#8ba69c'; x.fillText(b.sub, 600, 545);
const who = d.username ? '@' + d.username : d.memberId ? 'member #' + d.memberId : '';
if (who) { x.fillStyle = '#43e8c3'; x.font = 'bold 30px Sora, sans-serif'; x.fillText(who, 600, 590); }
x.textAlign = 'left';
try {
c.toBlob(bl => {
const a = document.createElement('a');
a.href = URL.createObjectURL(bl);
a.download = 'instantadpay-' + key + '-badge.png';
a.click();
setTimeout(() => URL.revokeObjectURL(a.href), 5000);
IAP.status('Badge image saved — share it anywhere.', 'ok');
}, 'image/png');
} catch (e) { IAP.status('Could not generate the image.', 'bad'); }
}
// 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: 'Payouts on', sub: 'wallet linked', hit: !!d.memberId },
{ label: 'First buyer', sub: '50% of every pack', hit: b >= 1 },
{ label: 'Level 2', sub: '2 buyers · +20%', hit: b >= 2 },
{ label: 'Level 3', sub: '5 buyers · +10%', hit: b >= 5 }
];
const cur = steps.findIndex(s => !s.hit);
el.innerHTML = steps.map((s, i) =>
'
').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', () => { const u = prompt('Link URL (https://…)'); if (u) { $('bcEd').focus(); 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'].includes(which) ? which : 'watch';
const w = $('earn-watch'), i = $('earn-inbox'), v = $('earn-videos');
if (w) w.hidden = earnSub !== 'watch';
if (i) i.hidden = earnSub !== 'inbox';
if (v) v.hidden = earnSub !== 'videos';
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 earnRefresh();
}
document.querySelectorAll('.subtabs [data-earn]').forEach(b =>
b.addEventListener('click', () => setEarnSub(b.dataset.earn)));
async function loadInbox() {
try {
const r = await (await fetch('/api/my/inbox')).json();
if (r.error) return;
$('ibRewardNote').textContent = '+' + r.readCredits + ' credits per real read (up to '
+ r.readCap + ' rewarded reads a day)';
const el = $('ibList');
$('inboxReadCard').hidden = true;
$('inboxListCard').hidden = false;
setInboxBadge(r.unread);
if (!r.items.length) {
el.innerHTML = '
No solo ads yet. When a member sends one, it lands here — and reading it pays.
';
return;
}
el.innerHTML = '';
for (const i of r.items) {
const d = document.createElement('div');
d.className = 'ib-row' + (i.read ? '' : ' unread');
d.innerHTML = ''
+ (i.rewarded ? 'claimed' : i.read ? '' : 'new')
+ '' + new Date(i.delivered).toLocaleDateString() + '';
d.querySelector('.sub').textContent = i.subject || '(no subject)';
d.querySelector('.from').textContent = 'from ' + (i.fromName || 'a member');
d.addEventListener('click', () => openInboxItem(i.id));
el.appendChild(d);
}
} catch (e) {}
}
async function openInboxItem(id) {
try {
const r = await (await fetch('/api/my/inbox/' + id)).json();
if (r.error) { IAP.status(r.error, 'bad'); return; }
$('inboxListCard').hidden = true;
$('inboxReadCard').hidden = false;
$('ibSubject').textContent = r.subject || '(no subject)';
$('ibMeta').textContent = 'from ' + (r.fromName || 'a member') + ' · ' + new Date(r.delivered).toLocaleString();
$('ibBody').innerHTML = r.body || ''; // whitelist-sanitized on the server at submit
const mv = $('ibMedia');
mv.hidden = !r.mediaUrl;
mv.innerHTML = !r.mediaUrl ? ''
: r.mediaType === 'video'
? ''
: '';
// the read reward needs BOTH the dwell AND an actual click-through to the
// advertiser — the visit is what makes the ad worth the sender's credits
const visit = $('ibVisit');
visit.href = r.url;
visit.textContent = r.ctaLabel || 'Learn more';
visit.target = '_blank';
const btn = $('ibClaimBtn');
clearInterval(ibTimer);
if (r.rewarded) {
btn.hidden = true;
visit.classList.remove('cta-need');
$('ibHint').textContent = 'Read reward already claimed for this one.';
return;
}
let dwellDone = false;
let visited = !!r.visited;
btn.hidden = false;
btn.disabled = true;
visit.classList.toggle('cta-need', !visited);
let left = r.dwell;
const refresh = () => {
if (!dwellDone) { btn.textContent = 'Read it — claim in ' + left + 's'; return; }
if (!visited) { btn.textContent = 'Claim +' + r.reward + ' — visit the ad first'; btn.disabled = true; return; }
btn.textContent = 'Claim +' + r.reward + ' credits'; btn.disabled = false;
};
$('ibHint').textContent = 'Read the message, click through to the advertiser, then claim your credits.';
refresh();
// countdown pauses off-tab; the server separately enforces the dwell on its own clock
ibTimer = setInterval(() => {
if (document.visibilityState !== 'visible' || !document.hasFocus()) return;
left -= 1;
if (left > 0) { refresh(); return; }
clearInterval(ibTimer);
dwellDone = true;
refresh();
}, 1000);
// clicking the CTA records the visit (and counts the advertiser's click)
visit.onclick = async () => {
visited = true;
visit.classList.remove('cta-need');
try { await fetch('/api/my/inbox/' + id + '/visit', { method: 'POST' }); } catch (e2) {}
refresh();
};
btn.onclick = async () => {
try {
const c = await api('/api/my/inbox/' + id + '/claim');
IAP.status('+' + c.credited + ' credits for reading. They spend like any earned credits.', 'ok');
btn.hidden = true;
$('ibHint').textContent = 'Claimed. Head back for the next one.';
loadDashboard();
} catch (e2) { IAP.status(e2.message, 'bad'); }
};
} catch (e) {}
}
$('ibBack').addEventListener('click', ev => { ev.preventDefault(); clearInterval(ibTimer); loadInbox(); });
// ── promo tools: Branded Voice copy, personalized with the member link ──
const PROMO_POSTS = [
'A membership site where money is handled by code, not people. Every purchase splits instantly to sponsor wallets on the Polygon blockchain. Nothing to withdraw. The money just lands in your wallet. Plus you earn ad credits for viewing ads while you\'re there. {{LINK}}',
'No withdrawal button. Think about that. A smart contract on Polygon splits every payment the second it hits. 50% to the sponsor. 20% to the next level. 10% to the next. Lands straight in your own wallet. No button to push. No waiting. Just money where it belongs. See how it works: {{LINK}}',
'Every payment is public on the blockchain. You can watch the ledger move in real time. Every split, every wallet, every transaction. Nothing hidden. Nothing you have to take on faith. That\'s the difference between a platform that asks for trust and one where trust isn\'t needed. See for yourself: {{LINK}}'
];
const PROMO_SWIPE = {
subject: 'Your Wallet Gets Paid Instantly..',
body: 'You know the usual drill. Someone buys on your link, you wait for a payout. Maybe days. Maybe an approval hold. Maybe a "your account is under review."\n\nInstantAdPay doesn\'t work like that.\n\nA smart contract on the Polygon blockchain handles every purchase the second it happens. 50% to the sponsor. 20% to the next level. 10% to the one after that. 20% to the platform. Each split lands directly in your own wallet. No withdrawal button. No "request payout." No approval queue.\n\nThe money just shows up.\n\nYou can watch every transaction on the public ledger. Real time. Anyone can verify it.\n\nFree to join. Packages from $5 to $250. No income promises. It\'s advertising, not investing.\n\n{{LINK}}'
};
function promoBlock(text) {
const div = document.createElement('div');
div.className = 'promo-block';
div.textContent = text;
const btn = document.createElement('button');
btn.className = 'btn small sec';
btn.textContent = 'Copy';
btn.addEventListener('click', async () => {
try { await navigator.clipboard.writeText(text); IAP.status('Copied. Paste it anywhere.', 'ok'); }
catch (e) { IAP.status('Copy failed. Select the text instead.', 'bad'); }
});
div.appendChild(btn);
return div;
}
function fillPromo(link) {
const posts = $('promoPosts');
if (!posts || posts.dataset.filled === link) return;
posts.dataset.filled = link;
posts.innerHTML = '';
for (const p of PROMO_POSTS) posts.appendChild(promoBlock(p.replace('{{LINK}}', link)));
const sw = $('promoSwipeWrap');
sw.innerHTML = '';
sw.appendChild(promoBlock('Subject: ' + PROMO_SWIPE.subject + '\n\n' + PROMO_SWIPE.body.replace('{{LINK}}', link)));
}
// ── profile ── (busy2 defers the busy lookup past its TDZ)
$('pfSaveBtn').addEventListener('click', busy2($('pfSaveBtn'), async () => {
const r = await api('/api/my/profile', { username: $('pfUsername').value });
IAP.status('You are @' + r.account.username + ' now.', 'ok');
await render();
}));
// ── in-dashboard package buying ──
const PKG = { 1: 'Micro', 2: 'Activation', 3: 'Builder', 4: 'Growth', 5: 'Leader' };
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 = '