Files
linkspin/public/assets/ads-screen.js
T
martbost e545343fe0 Michael Camire fixes + hub shells in the tank (Marty 2026-11-14, LinkSpin Support)
1. Top-up across positions: an ad burns from ONE position, and topUpCampaign only looked at the ad's
   own position (or the main one when the list row had no memberId), so credits bought on a linked
   position could never top up the ad. Ported from InstantAdPay 2026-09-27 (Jim Watts): the ad's real
   member id is read from the campaign row; when it cannot cover, the refusal names where the free
   credits are and offers switchOptions; with the member's yes (switchTo, only a position on the
   account) moveFunding settles what the ad already ran up on the OLD position, moves the ad, then
   tops up. Ads screen asks in-page (own dialog) and retries. Create already had the largest-position guard.
2. Toasts: errors stay until closed (close button, role=alert), other notes 3.5 to 9 s by length.
3. Banner Spin per-banner clicks: his 3 clicks were all unmatched (no view on record for that browser),
   so they landed on the fallback row and every banner said 0. Click matching now also tries the same
   connection (daily-salted IP-only hash) when the browser key finds nothing (mail/exchange app view,
   click opened in the phone browser), view notes last 60 min instead of 15, and the stats split
   'Fallback shown' from 'Clicks not tied to a banner' so the rows add up to the total. History is not
   backfilled: views were never stored per visitor, so old clicks cannot be tied reliably.
4. Holding tank: hub-made waiting accounts with no sponsor are in the tank (waiting, rescue, readyTick
   read listAll with { shells: true }; 'hub-shell' no longer holds anyone back). Locked / sponsored /
   unknown, grace, 2-adoption cap unchanged; readyTick still never switches a shell on;
   accounts.listAll default unchanged (mailings skip shells).

Assets: cr.css, cr-shell.js, ads-screen.js ?v=20261114tu, banner-spin.js ?v=20261114bc.
QA: walk member 0 bugs (36 ok), netconv 57/57, networksso ALL PASSED, tank-hold all passed (new hub
shell part), profile policy 16/16, new topup-positions 8/8, new bannerspin-attrib 7/7, bannerspin e2e
75/75, hubsync 15 checks, tank-cap 15/15, sponsorfollow 30/30.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 11:59:38 -06:00

210 lines
31 KiB
JavaScript

// LinkSpin Ads screen (2026-09-29): buy banner / text / login ads on the engine's campaign API, watch delivery across the
// viewer, member zones and the partner network, and earn credits by viewing. Types are limited to the three Marty chose.
(function () {
const $ = id => document.getElementById(id); const esc = CR.esc, fmt = CR.fmt, api = CR.api, toast = CR.toast, dialog = CR.dialog;
let D = null, EARN = null, TYPE = 'banner', SPINS = [], HOSTS = [], IMG = '';
CR.mount({ active: 'ads', title: 'Ads', sub: 'loading', actions: '<button class="btn pri" type="button" id="newBtn">+ New ad</button>' });
const NOTE = {
banner: 'Runs in the ad viewer, in every member zone on outside sites, and on the partner network. Views are timed on the server. Spends purchased or earned credits.',
text: 'A headline and one line. Runs in the ad viewer and on the partner network. Spends purchased or earned credits.',
login: 'Your page, full screen, to every member right after they sign in. A slot is a flat buy of purchased credits for a fixed run of unlimited sign-in impressions, paid once and never charged per day. No creative needed: the page is the ad.'
};
// login slots (same rule as InstantAdPay): one flat price, a fixed run, a cap on member slots live at once
const slotInfo = () => { const r = (D && D.rates) || {}; const ls = (D && D.loginSlots) || {}; const max = ls.max || r.loginSlotsMax || 3;
return { credits: ls.credits || r.loginSlotCredits || 1000, days: ls.days || r.loginSlotDays || 30, max, used: ls.used || 0, queued: ls.queued || 0, free: ls.free != null ? ls.free : max }; };
// prepaid queue (Marty, 2026-10-23): when every slot is taken you pay now for a place in line; first paid, first served
const nextPlace = () => (D && D.loginNext) || { place: 1, estStartCt: null };
const estText = ct => ct ? (ct === 'any minute now' ? 'Estimated start: any minute now.' : 'Estimated start: ' + ct + ' (Central time).') + ' This is an estimate: it moves earlier if a running slot is paused, and can move if the number of slots changes.' : 'There is no start estimate yet.';
const loginNote = () => { const L = slotInfo();
return 'Your page, full screen, to every member right after they sign in. A slot is ' + fmt(L.credits) + ' purchased credits for ' + L.days + ' days of unlimited sign-in impressions, paid once and never charged per day. ' + L.max + ' slots at a time. When all are taken you can reserve the next one: you pay now, your ' + L.days + ' days start when a slot frees up, first paid first served, and cancelling before it starts refunds you in full. No creative needed: the page is the ad.'; };
const host = u => { try { return new URL(u).hostname.replace(/^www\./, ''); } catch (e) { return u; } };
async function load() {
try { [D, EARN] = await Promise.all([CR.get('/api/my/campaigns'), CR.get('/api/my/earn')]); } catch (e) { CR.sub('could not load'); return; }
const cs = D.campaigns || []; const live = cs.filter(c => c.status === 'active');
{ const sel = $('fAud'); if (sel) { const keep = sel.value; sel.innerHTML = '<option value="">Everyone</option>' + (D.audiences || []).map(a => '<option value="' + a.id + '">' + esc(a.name) + ' (' + fmt(a.size30) + ')</option>').join(''); sel.value = keep; sel.onchange = () => { $('fAudModeRow').hidden = !sel.value; }; } }
const views = cs.reduce((n, c) => n + (c.imps || 0) + (c.impsNas || 0) + (c.impsSyn || 0), 0);
const synN0 = Math.max(1, Math.floor(Number(D.rates && D.rates.synRateDivisor) || 1)); // network rate (Marty, 2026-10-27, 4:1)
const synT = Math.max(1, Math.floor(Number(D.rates && D.rates.synRateDivisorText != null ? D.rates.synRateDivisorText : synN0) || 1)); // text ads (Marty, 2026-11-12, 1/10)
const offTxt = c => { const synN = c.type === 'text' ? synT : synN0; return (c.impsNas ? '<br><span class="muted" style="font-size:11px">+' + fmt(c.impsNas) + ' network' + (synN > 1 ? ' at 1/' + synN : '') + '</span>' : '')
+ (c.impsSyn ? '<br><span class="muted" style="font-size:11px">+' + fmt(c.impsSyn) + ' partner zones' + (synN > 1 ? ' at 1/' + synN : '') + '</span>' : ''); };
CR.sub(live.length + ' live · ' + fmt(D.availableCredits) + ' credits available');
const hours = new Array(24).fill(0); Object.values(D.hours || {}).forEach(a => (a || []).forEach((n, i) => { hours[i] += Number(n) || 0; })); // last 7 days by UTC hour, all campaigns
const week = hours.reduce((a, b) => a + b, 0);
$('tiles').innerHTML = [
CR.tile({ k: 'Credits available', v: fmt(D.availableCredits), hi: true, note: D.earnedCredits ? fmt(D.earnedCredits) + ' earned free to spend' : '' }),
CR.tile({ k: 'In live campaigns', v: fmt(D.inCampaigns), note: live.length + ' live ad' + (live.length === 1 ? '' : 's') }),
CR.tile({ k: 'Views delivered', v: fmt(views), series: week ? hours : null, note: week ? fmt(week) + ' in 7 days, by hour' : '' }),
CR.tile({ k: 'Today\'s viewing', v: EARN.views + ' / ' + EARN.target, note: EARN.streakDay > 1 ? 'streak day ' + EARN.streakDay : '' })].join('');
const r = D.rates || {};
$('rateLine').textContent = 'Rates: ' + r.bannerCreditsPerBatch + ' credits per ' + r.bannerBatch + ' banner views, ' + r.textCreditsPerBatch + ' per ' + r.textBatch + ' text views' + (synN0 > 1 ? ' here (views on the partner network and in other members\u2019 zones cost 1/' + synN0 + ' of that for banners' + (synT !== synN0 ? ', 1/' + synT + ' for text ads' : '') + ')' : '') + ', ' + fmt(slotInfo().credits) + ' purchased credits for a ' + slotInfo().days + '-day login slot (' + (slotInfo().free ? slotInfo().free + ' of ' + slotInfo().max + ' open' : 'all ' + slotInfo().max + ' taken' + (slotInfo().queued ? ', ' + slotInfo().queued + ' in line' : '') + ', reserve the next one') + '). Viewing pays ' + EARN.claimCredits + ' credits for ' + EARN.target + ' timed views a day.';
// traffic-light status (2026-10-20): live green, running low amber (80%+ of the budget spent), out red, paused grey
const stKey = c => c.status === 'queued' ? 'queued' : c.status === 'cancelled' ? 'cancelled' : c.scheduled ? 'sched' : c.status === 'active' ? (c.type !== 'login' && c.budget > 0 && c.spent / c.budget >= 0.8 ? 'low' : 'live') : c.status === 'paused' ? 'paused' : c.status === 'out' ? 'out' : c.status === 'done' ? 'ended' : '';
const ST_LABEL = { queued: 'In line', cancelled: 'Cancelled, refunded', sched: 'Scheduled', live: 'Live', low: 'Running low', paused: 'Paused', out: 'Out of credits', ended: 'Ended' };
const st = c => { const k = stKey(c); return '<span class="stg" data-st="' + k + '">' + (ST_LABEL[k] || esc(c.status)) + '</span>'; };
const QM = {}; (D.loginQueue || []).forEach(q => { QM[q.id] = q; });
const qCell = c => { const q = QM[c.id]; return '<span class="muted">full page<br><span style="font-size:12px"><b>#' + (q ? q.place : '?') + ' in line</b>, paid' + (q && q.estStartCt ? '<br>' + (q.estStartCt === 'any minute now' ? 'starts any minute now' : 'est. start ' + esc(q.estStartCt) + ' CT (an estimate)') : '') + '</span></span>'; };
const cr = c => c.status === 'queued' ? qCell(c) : c.status === 'cancelled' ? '<span class="muted">full page<br><span style="font-size:12px">' + fmt(c.refunded || 0) + ' credits refunded</span></span>' : c.type === 'banner' ? (c.imageUrl ? '<img class="thumb" src="' + esc(c.imageUrl) + '" alt="">' : '') + '<span class="mono muted" style="font-size:11px">' + c.width + 'x' + c.height + '</span>' : c.type === 'text' ? '<b>' + esc(c.title) + '</b><br><span class="muted" style="font-size:12px">' + esc(c.body || '') + '</span>' : '<span class="muted">full page' + (c.type === 'login' && c.expires ? '<br><span style="font-size:12px">' + (c.expires > Date.now() ? 'slot ends ' : 'ended ') + new Date(c.expires).toLocaleDateString(undefined, { month: 'short', day: 'numeric' }) + '</span>' : '') + '</span>';
$('rows').innerHTML = cs.length ? cs.map(c => '<div class="rw st-row" data-st="' + stKey(c) + '"><div><b>' + esc(c.name) + '</b> <span class="tag t">' + esc(c.type) + '</span>' + (c.audience ? ' <span class="tag plain" title="audience">' + esc((((D && D.audiences) || []).find(a => a.id === c.audience) || {}).name || 'audience') + (c.audienceMode === 'exclude' ? ' · excluded' : '') + '</span>' : '') + '<br><span class="mono muted" style="font-size:11px">#' + c.id + ' · ' + esc(host(c.targetUrl)) + (c.geo ? ' · tiers ' + esc(c.geo) : '') + (c.dailyCap ? ' · cap ' + c.dailyCap + '/day' : '') + '</span></div><div>' + cr(c) + '</div><div><span class="num">' + fmt(c.status === 'cancelled' ? 0 : c.spent) + '</span><span class="muted"> / ' + fmt(c.budget) + (c.status === 'queued' ? ' paid' : '') + '</span><div class="bar st"><i style="width:' + (c.status === 'cancelled' ? 0 : Math.min(100, Math.round(100 * c.spent / Math.max(1, c.budget)))) + '%"></i></div></div><span class="r num">' + fmt(c.imps) + offTxt(c) + '</span><span class="r num">' + fmt(c.clicks) + '</span><span>' + st(c) + '</span><span style="display:flex;gap:6px;justify-content:flex-end;flex-wrap:wrap">'
+ (c.status === 'active' ? '<button class="btn sm" type="button" data-pause="' + c.id + '">Pause</button>' : c.status === 'paused' ? '<button class="btn sm" type="button" data-resume="' + c.id + '">Resume</button>' : '')
+ (['active', 'paused', 'out'].includes(c.status) && c.type !== 'login' ? '<button class="btn sm" type="button" data-top="' + c.id + '">Top up</button>' : '')
+ (c.status === 'queued' ? '<button class="btn sm" type="button" data-qcancel="' + c.id + '" title="Leave the line: the ' + fmt(c.budget) + ' credits you paid come back in full">Cancel and refund</button>' : '')
+ (!['done', 'cancelled'].includes(c.status) ? '<button class="btn sm" type="button" data-edit="' + c.id + '" title="' + (c.edits ? 'Edit the link, ' + (c.type === 'banner' ? 'image' : c.type === 'text' ? 'text' : 'name') + ' (' + fmt(D.editFee) + ' credits)' : 'Fix the link, ' + (c.type === 'banner' ? 'image' : c.type === 'text' ? 'text' : 'name') + ' (first edit free)') + '">Edit</button>' : '') + '</span></div>').join('')
: '<div class="rw"><span class="muted">No ads yet. Launch one: a banner, a text ad or a login-ad slot.</span></div>';
if (D.gauntletPending) $('earnNote').insertAdjacentHTML('afterend', '<div class="muted" style="margin-top:8px">Your welcome credits unlock after the short welcome tour on <a href="/tools">the classic dashboard</a>.</div>');
$('foot').textContent = 'views = views here on LinkSpin; network = the partner ad network; partner zones = other members\u2019 zones on their own sites' + (synN0 > 1 ? ' (network and partner-zone views cost 1/' + synN0 + ' of the rate here, so ' + synN0 + ' of them cost what 1 view here does' + (synT !== synN0 ? '; text ads 1/' + synT : '') + ')' : '') + ' · a paused ad keeps its credits · unspent credits return when an ad ends';
$('rows').querySelectorAll('[data-pause]').forEach(b => b.addEventListener('click', () => act('/api/my/campaigns/' + b.dataset.pause + '/pause')));
$('rows').querySelectorAll('[data-resume]').forEach(b => b.addEventListener('click', () => act('/api/my/campaigns/' + b.dataset.resume + '/resume')));
// An ad pays from ONE position (the contract burns from that member id). When the ad's own position cannot
// cover a top-up but another of the member's positions can, the server says so (switchOptions) and the member
// can move the ad to that position and pay from there (Michael Camire 2026-11-14, ported from InstantAdPay).
const topUpReq = async (id, credits, switchTo) => (await fetch('/api/my/campaigns/' + id + '/topup', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(switchTo ? { credits, switchTo } : { credits }) })).json();
$('rows').querySelectorAll('[data-top]').forEach(b => b.addEventListener('click', async () => {
const multi = (D.positionCount || 0) > 1;
const v = await dialog({ title: 'Top up #' + b.dataset.top, text: 'Add credits to this ad. You have ' + fmt(D.availableCredits) + ' available' + (multi ? ' across your positions; an ad pays from one position' : '') + '.', fields: [{ k: 'credits', label: 'Credits to add', value: '25', mono: true }], ok: 'Add' }); if (!v) return;
const credits = Number(v.credits);
try {
let r = await topUpReq(b.dataset.top, credits);
if (r.error && r.switchOptions && r.switchOptions.length) {
const o = r.switchOptions[0];
const ok = await dialog({ title: 'Pay from position #' + o.memberId + '?', text: r.error + ' Move this ad to position #' + o.memberId + ' (' + fmt(o.free) + ' free) and add the ' + fmt(credits) + ' credits from there? Views from now on are paid from #' + o.memberId + '; what the ad already ran up stays on its old position.', ok: 'Pay from #' + o.memberId });
if (!ok) return;
r = await topUpReq(b.dataset.top, credits, o.memberId);
}
if (r.error) throw new Error(r.error);
toast('Topped up: ' + fmt(r.added) + ' credits added' + (r.paidFrom ? ', paid from position #' + r.paidFrom : '') + (r.reactivated ? '. The ad is live again.' : '.')); load();
} catch (e) { toast(e.message, true); }
}));
$('rows').querySelectorAll('[data-qcancel]').forEach(b => b.addEventListener('click', () => cancelReservation(Number(b.dataset.qcancel))));
$('rows').querySelectorAll('[data-edit]').forEach(b => b.addEventListener('click', () => openEdit(Number(b.dataset.edit))));
{ const w = $('loginWhere'); if (w) w.textContent = 'full screen to every member right after they sign in: ' + fmt(slotInfo().credits) + ' purchased credits for a ' + slotInfo().days + '-day slot, ' + slotInfo().max + ' slots at a time. When all are taken, reserve the next one: pay now, it starts when a slot frees, and a cancel before then refunds in full'; }
{ const cl = D.creditLog || []; const box = $('creditLog'); if (box) { box.parentElement.hidden = !cl.length; box.innerHTML = cl.map(x => '<div style="display:flex;justify-content:space-between;gap:10px;padding:5px 0;border-bottom:1px solid var(--chrome-line)"><span>' + esc(x.reason) + (x.campaignId ? ' <span class="mono muted" style="font-size:11px">#' + x.campaignId + '</span>' : '') + '<br><span class="muted" style="font-size:11px">' + new Date(x.ts).toLocaleString('en-US', { timeZone: 'America/Chicago', month: 'short', day: 'numeric', hour: 'numeric', minute: '2-digit' }) + ' CT</span></span><span class="num mono" style="white-space:nowrap">' + (x.delta > 0 ? '+' : '') + (x.delta ? fmt(x.delta) : '') + '</span></div>').join(''); } }
slotChip(); if (!$('composer').hidden) setType(TYPE);
earnPaint();
{ const hm = /^#edit=(\d+)$/.exec(location.hash || ''); if (hm) { history.replaceState(null, '', location.pathname + location.search); openEdit(Number(hm[1])); } } // /tools campaign list links here
}
// -- edit an ad (2026-10-18): fix the link, the image or the text. The first edit of each ad is free, then D.editFee credits.
// Type, size, budget, countries, schedule and audience are the buy itself and stay a new campaign.
const feeNote = c => c.status === 'queued' ? 'Edits are free while this ad waits in line, and your one free correction stays for when it runs.' : !c.edits ? 'This edit is free (your one free correction).' : (D.editFee ? 'This edit costs ' + fmt(D.editFee) + ' credits.' : 'Edits are free right now.');
async function openEdit(id) {
const c = ((D && D.campaigns) || []).find(x => x.id === id); if (!c) { toast('That ad is not in your list.', true); return; }
const fields = [{ k: 'name', label: 'Name', value: c.name, max: 60 }, { k: 'targetUrl', label: 'Where the click goes', value: c.targetUrl, mono: true }];
if (c.type === 'banner') fields.push({ k: 'imageUrl', label: 'Image URL (' + c.width + 'x' + c.height + ')', value: c.imageUrl || '', mono: true });
if (c.type === 'text') fields.push({ k: 'title', label: 'Headline (60)', value: c.title || '', max: 60 }, { k: 'body', label: 'One line (140)', value: c.body || '', max: 140 });
const last = (c.editLog || []).slice(-1)[0];
const html = '<div class="muted" style="margin:8px 0" id="edFee"><b>' + esc(feeNote(c)) + '</b> ' + (c.status === 'queued' ? '' : c.edits ? 'Your free correction on this ad is used.' : 'After this one, each edit costs ' + fmt(D.editFee) + ' credits.') + '</div>'
+ '<div class="muted" style="font-size:12px;margin-bottom:6px">The type, size, budget, countries, schedule and audience stay as they are. To change those, start a new ad.' + (last ? ' Last edited ' + new Date(last.ts).toLocaleString() + '.' : '') + '</div>'
+ (c.type === 'banner' ? '<label class="lbl">Or upload a new image (PNG, JPG, WebP, GIF up to 3 MB)<input class="field" id="edFile" type="file" accept="image/png,image/jpeg,image/webp,image/gif"></label><div class="muted" style="margin:6px 0 4px">Preview at real size</div><div id="edPrev" style="max-width:100%;overflow:auto"></div>' : '')
+ (c.type === 'login' ? '<div class="muted" style="font-size:12px">A login ad shows the page itself, full screen, so the link is the ad.</div>' : '');
const wait = dialog({ title: 'Edit ad #' + c.id + ' (' + c.type + ')', html, fields, ok: 'Review changes' });
if (c.type === 'banner') { // the dialog is in the page now: wire the preview and the uploader
const host = $('crModalHost'), inp = host.querySelector('#dlg-imageUrl'), prev = host.querySelector('#edPrev');
const paint = () => { const u = inp.value.trim(); prev.innerHTML = /^https?:\/\//i.test(u) ? '<img src="' + esc(u) + '" alt="" style="width:' + c.width + 'px;height:' + c.height + 'px;max-width:none;display:block;border:1px solid var(--chrome-line);background:var(--inset)">' : '<span class="muted">No image yet</span>'; };
inp.addEventListener('input', paint); paint();
host.querySelector('#edFile').addEventListener('change', async e => { const f = e.target.files[0]; if (!f) return; try { const r = await (await fetch('/api/my/upload', { method: 'POST', headers: { 'Content-Type': f.type }, body: f })).json(); if (r.error) throw new Error(r.error); inp.value = location.origin + r.url; paint(); toast('Uploaded.'); } catch (er) { toast(er.message, true); } });
}
const v = await wait; if (!v) return;
const label = { name: 'name', targetUrl: 'link', imageUrl: 'image', title: 'headline', body: 'text line' };
const changed = Object.keys(v).filter(k => String(v[k]).trim() !== String(c[k] || '').trim());
if (!changed.length) { toast('Nothing changed.'); return; }
const paidEdit = c.status !== 'queued' && c.edits && D.editFee;
const ok = await dialog({ title: 'Save the new ' + changed.map(k => label[k]).join(', ') + '?', text: feeNote(c) + (paidEdit ? ' It comes out of your earned credits first, then purchased.' : ''), ok: paidEdit ? 'Save and pay ' + fmt(D.editFee) : 'Save' });
if (!ok) return;
const body = {}; changed.forEach(k => { body[k] = v[k].trim(); });
try { const r = await api('/api/my/campaigns/' + c.id + '/edit', body); toast('Saved.' + (r.fee ? ' ' + fmt(r.fee) + ' credits charged.' : '') + (r.warn ? ' ' + r.warn : '')); load(); }
catch (e) { toast(e.message, true); }
}
async function cancelReservation(id) {
const c = ((D && D.campaigns) || []).find(x => x.id === id); if (!c) return;
const q = (D.loginQueue || []).find(x => x.id === id);
const ok = await dialog({ title: 'Cancel reservation #' + id + '?', text: 'You leave the line' + (q ? ' (you are #' + q.place + ')' : '') + ' and the ' + fmt(c.budget) + ' credits you paid come back to you in full, as purchased credits. If you reserve again later, you join at the back of the line.', ok: 'Cancel and refund', no: 'Keep my place', danger: true });
if (!ok) return;
try { const r = await api('/api/my/campaigns/' + id + '/cancel-reservation', {}); toast('Cancelled. ' + fmt(r.refunded) + ' credits refunded.'); load(); } catch (e) { toast(e.message, true); }
}
async function act(path) { try { await api(path, {}); load(); } catch (e) { toast(e.message, true); } }
// -- earn by viewing: the engine's fraud-guarded flow (server-timed dwell + a human check) runs inside /view/<token>
function earnPaint() {
const s = EARN; if (!s) return;
{ const g = $('earnGauge'); if (g) { const n = Math.max(1, s.target); g.innerHTML = Array.from({ length: n }, (_, i) => '<i class="' + (i < s.views ? 'on' : '') + '"></i>').join(''); g.style.gridTemplateColumns = 'repeat(' + n + ',1fr)'; } }
const done = s.views >= s.target;
$('earnLine').textContent = s.claimed ? 'Claimed for today' + (s.streakDay > 1 ? ' (streak day ' + s.streakDay + ')' : '') + '. Tomorrow pays ' + s.nextClaim + '.' : done ? 'Set complete. Claim your ' + s.claimCredits + ' credits.' : s.views + ' of ' + s.target + ' viewed. Then claim ' + s.claimCredits + ' credits' + (s.streakDay > 1 ? ' (streak day ' + s.streakDay + ')' : '') + '.';
$('earnClaim').hidden = !(done && !s.claimed); $('earnNext').hidden = done;
$('earnNote').textContent = (s.earnedAvailable != null ? s.earnedAvailable : s.earned) + ' earned credits free to spend' + (s.reserved ? ', ' + s.reserved + ' working in live ads' : '') + '. Each view is a full page, timed on the server, with a quick check at the end.';
}
async function earnRefresh() { try { EARN = await CR.get('/api/my/earn'); earnPaint(); } catch (e) {} }
let vt = 0;
$('earnNext').addEventListener('click', async () => {
const type = ['banner', 'text'][vt++ % 2]; let r = null;
try { r = await CR.get('/api/my/earnview?type=' + type); } catch (e) { toast(e.message, true); return; }
if (!r || !r.ad || !r.viewUrl) { toast(r && r.status && r.status.views >= r.status.target ? 'Set complete for today.' : 'No member ads are live right now. Views resume the moment a campaign runs.', true); earnRefresh(); return; }
openView(r.viewUrl);
});
function openView(url) {
closeView(); const back = document.createElement('div'); back.id = 'adOverlay'; back.style.cssText = 'position:fixed;inset:0;z-index:100000;background:#050912;display:flex;flex-direction:column';
const x = document.createElement('button'); x.type = 'button'; x.setAttribute('aria-label', 'Close ad'); x.textContent = '✕'; x.style.cssText = 'position:absolute;top:10px;right:12px;z-index:2;width:40px;height:40px;border-radius:50%;border:1px solid rgba(255,255,255,.25);background:rgba(6,10,16,.85);color:#fff;font-size:20px;font-weight:700;cursor:pointer'; x.addEventListener('click', closeView);
const f = document.createElement('iframe'); f.src = url; f.style.cssText = 'flex:1;width:100%;border:0;background:#050912'; back.appendChild(f); back.appendChild(x); document.body.appendChild(back); document.body.style.overflow = 'hidden';
}
function closeView() { const m = $('adOverlay'); if (m) m.remove(); document.body.style.overflow = ''; earnRefresh(); }
window.addEventListener('message', e => { if (e.origin !== location.origin || !e.data) return; if (e.data.t === 'iap-view-close') closeView(); else if (e.data.t === 'iap-view-done') earnRefresh(); });
window.addEventListener('storage', e => { if (e.key === 'iap-view-done') earnRefresh(); });
$('earnClaim').addEventListener('click', async () => { try { const r = await api('/api/my/claim', {}); toast('+' + r.credited + ' credits' + (r.streakDay > 1 ? ', streak day ' + r.streakDay : '') + '. Spend them on an ad.'); load(); } catch (e) { toast(e.message, true); } });
// -- composer
function setType(t) { TYPE = t; document.querySelectorAll('#typeChips .chip').forEach(c => c.classList.toggle('on', c.dataset.t === t)); $('typeNote').textContent = t === 'login' ? loginNote() : NOTE[t]; $('bannerFields').hidden = t !== 'banner'; $('textFields').hidden = t !== 'text'; $('fCap').parentElement.hidden = t === 'login';
const L = slotInfo(), full = t === 'login' && !L.free; const fb = $('fBudget');
if (t === 'login') { fb.dataset.keep = fb.dataset.keep || fb.value; fb.value = L.credits; fb.readOnly = true; } else { if (fb.readOnly && fb.dataset.keep) fb.value = fb.dataset.keep; delete fb.dataset.keep; fb.readOnly = false; }
$('fGo').disabled = false; $('fGo').textContent = full ? 'Reserve the next slot' : 'Launch'; $('fGo').title = full ? 'All login-ad slots are taken: pay now for a place in line' : '';
cost(); preview(); }
// a login slot is paid from ONE position (2026-11-04): say what each position has free and stop the buy up front when none covers it
const loginShort = () => { const F = D && D.loginFunds; return !!(F && F.best < slotInfo().credits); };
function fundsLine() { const F = D && D.loginFunds; if (!F) return ''; const L = slotInfo();
const per = (F.per || []).length > 1 ? ' (' + F.per.map(x => '#' + x.memberId + ': ' + fmt(x.avail)).join(', ') + ')' : '';
return '<span style="display:block;line-height:1.7;margin-top:4px' + (loginShort() ? ';color:var(--bad,#c0392b)' : '') + '">Paid from one position. '
+ (loginShort() ? 'None of yours has <b>' + fmt(L.credits) + '</b> purchased credits free on its own' + per + '. Buy a package on one position to bring it to ' + fmt(L.credits) + ', then come back.'
: 'Your best-funded position has <b>' + fmt(F.best) + '</b> purchased credits free' + per + '.') + '</span>'; }
function fundsGate() { if (TYPE !== 'login') return; const b = $('fGo'); b.disabled = loginShort(); if (loginShort()) b.title = 'No single position has ' + fmt(slotInfo().credits) + ' purchased credits free'; }
function slotChip() { const ch = document.querySelector('#typeChips .chip[data-t="login"]'); if (!ch || !D) return; const L = slotInfo(); ch.textContent = 'Login ad' + (L.free ? ' (' + L.free + ' of ' + L.max + ' open)' : ' (full, reserve the next)'); }
function cost() { const b = Math.floor(Number($('fBudget').value) || 0); const r = D ? D.rates : {}; let s = '';
if (TYPE === 'banner') s = 'about ' + fmt(Math.floor(b / (r.bannerCreditsPerBatch || 2) * (r.bannerBatch || 10))) + ' timed views';
else if (TYPE === 'text') s = 'about ' + fmt(Math.floor(b / (r.textCreditsPerBatch || 1) * (r.textBatch || 10))) + ' timed views';
else { const L = slotInfo(); $('fCost').innerHTML = (L.free
? '<b>' + fmt(L.credits) + '</b> purchased credits for <b>' + L.days + '</b> days of unlimited sign-in impressions · <b>' + L.free + '</b> of ' + L.max + ' slots open'
: '<span style="display:block;line-height:1.7">All <b>' + L.max + '</b> login-ad slots are taken' + (L.queued ? ', <b>' + L.queued + '</b> paid reservation' + (L.queued === 1 ? '' : 's') + ' in line' : '') + '. Reserve the next one: <b>' + fmt(L.credits) + '</b> purchased credits now and you would be <b>#' + nextPlace().place + '</b> in line. ' + esc(estText(nextPlace().estStartCt)) + ' Cancel before it starts for a full refund.</span>') + fundsLine(); fundsGate(); return; }
$('fCost').innerHTML = b >= 10 ? s.replace(/(about )([\d,]+)/, '$1<b>$2</b>') : 'minimum <b>10</b> credits'; }
function preview() { const p = $('prev'); if (TYPE === 'banner' && IMG) { const sz = ($('fSize').value || '728x90').split('x'); p.innerHTML = '<div class="muted" style="margin-bottom:6px">Preview</div><img src="' + esc(IMG) + '" alt="" style="max-width:100%;width:' + sz[0] + 'px;height:auto;border:1px solid var(--chrome-line);background:var(--inset)">'; }
else if (TYPE === 'text') p.innerHTML = '<div class="muted" style="margin-bottom:6px">Preview</div><div class="panel" style="max-width:420px"><b>' + esc($('fTitle').value || 'Your headline') + '</b><br><span class="ink2">' + esc($('fBody').value || 'One line under it.') + '</span><br><span class="mono muted" style="font-size:11px">' + esc(host($('fTarget').value || 'yoursite.com')) + '</span></div>';
else p.innerHTML = ''; }
document.querySelectorAll('#typeChips .chip').forEach(c => c.addEventListener('click', () => setType(c.dataset.t)));
['fBudget'].forEach(id => $(id).addEventListener('input', cost));
['fTitle', 'fBody', 'fTarget', 'fSize'].forEach(id => $(id).addEventListener('input', preview));
$('fImage').addEventListener('input', () => { IMG = $('fImage').value.trim(); preview(); });
$('fFile').addEventListener('change', async () => { const f = $('fFile').files[0]; if (!f) return; try { const r = await (await fetch('/api/my/upload', { method: 'POST', headers: { 'Content-Type': f.type }, body: f })).json(); if (r.error) throw new Error(r.error); IMG = location.origin + r.url; $('fImage').value = IMG; toast('Uploaded.'); preview(); } catch (e) { toast(e.message, true); } });
$('fSpin').addEventListener('change', () => { const code = $('fSpin').value; if (code) { $('fTarget').value = 'https://' + (HOSTS[0] || location.host) + '/r/' + code; preview(); } });
$('newBtn').addEventListener('click', async () => {
$('composer').hidden = false; $('composer').scrollIntoView({ behavior: 'smooth', block: 'start' });
if (D && D.bannerSizes && !$('fSize').options.length) $('fSize').innerHTML = D.bannerSizes.map(s => '<option value="' + s.id + '">' + esc(s.label) + '</option>').join('');
try { const r = await CR.get('/api/my/rotations'); SPINS = r.rotations || []; HOSTS = r.hosts || []; $('fSpin').innerHTML = '<option value="">pick a spin</option>' + SPINS.filter(s => !s.paused).map(s => '<option value="' + esc(s.code) + '">' + esc(s.name) + ' · /r/' + esc(s.code) + '</option>').join(''); } catch (e) {}
setType(TYPE);
});
$('fCancel').addEventListener('click', () => { $('composer').hidden = true; });
$('fGo').addEventListener('click', async () => {
const body = { type: TYPE, name: $('fName').value, targetUrl: $('fTarget').value.trim(), budget: Number($('fBudget').value), geo: $('fGeo').value };
if (TYPE !== 'login' && $('fCap').value) body.dailyCap = Number($('fCap').value);
if ($('fAud') && $('fAud').value) { body.audience = $('fAud').value; body.audienceMode = $('fAudMode').value; }
if (TYPE === 'banner') { body.size = $('fSize').value; body.imageUrl = $('fImage').value.trim(); }
if (TYPE === 'text') { body.title = $('fTitle').value; body.body = $('fBody').value; }
if (TYPE === 'login' && !slotInfo().free) { // the line: say exactly what happens before any credits move
const L = slotInfo(), nx = nextPlace();
const ok = await dialog({ title: 'Reserve the next login-ad slot?', text: 'All ' + L.max + ' slots are taken. You pay ' + fmt(L.credits) + ' purchased credits now and get place #' + nx.place + ' in line. Your ' + L.days + ' days start the moment a slot frees up (first paid, first served), and we let you know on the site and by email. ' + estText(nx.estStartCt) + ' Until it starts you can edit it for free, or cancel it for a full refund.', ok: 'Pay ' + fmt(L.credits) + ' and reserve' });
if (!ok) return;
body.reserve = true;
}
$('fGo').disabled = true;
try { const r = await api('/api/my/campaigns', body); const c = r.campaign || {};
toast(c.status === 'queued' ? 'Reserved and paid. You are #' + (c.place || '?') + ' in line. We let you know when it starts.' : TYPE === 'login' ? 'Launched. Your login-ad slot runs for ' + slotInfo().days + ' days.' : 'Launched. It is live in rotation now.');
$('composer').hidden = true; $('fName').value = ''; load(); } catch (e) {
// a login-ad failure stays on screen until read (the 2-second toast was missed, 2026-11-03)
if (TYPE === 'login') await dialog({ title: body.reserve ? 'Your reservation did not go through' : 'Your login ad did not launch', text: e.message, ok: 'OK', no: 'Close' }); else toast(e.message, true);
} finally { $('fGo').disabled = false; fundsGate(); }
});
CR.requireSession(load);
})();