// 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: '+ New ad ' });
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. One sponsor a day, purchased credits only. 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 views = cs.reduce((n, c) => n + (c.imps || 0) + (c.impsNas || 0), 0);
CR.sub(live.length + ' live · ' + fmt(D.availableCredits) + ' credits available');
$('tiles').innerHTML = [['Credits available', fmt(D.availableCredits)], ['In live campaigns', fmt(D.inCampaigns)], ['Views delivered', fmt(views)], ['Today\'s viewing', EARN.views + ' / ' + EARN.target]].map(([k, v], i) => '
' + k + ' ' + v + '
').join('');
const r = D.rates || {};
$('rateLine').textContent = 'Rates: ' + r.bannerCreditsPerBatch + ' credits per ' + r.bannerBatch + ' banner views, ' + r.textCreditsPerBatch + ' per ' + r.textBatch + ' text views, ' + r.loginCreditsPerDay + ' per day for the login spot. Viewing pays ' + EARN.claimCredits + ' credits for ' + EARN.target + ' timed views a day.';
const st = c => c.scheduled ? 'Scheduled ' : c.status === 'active' ? 'Live ' : c.status === 'paused' ? 'Paused ' : c.status === 'out' ? 'Out of credits ' : c.status === 'done' ? 'Ended ' : '' + esc(c.status) + ' ';
const cr = c => c.type === 'banner' ? (c.imageUrl ? ' ' : '') + '' + c.width + 'x' + c.height + ' ' : c.type === 'text' ? '' + esc(c.title) + ' ' + esc(c.body || '') + ' ' : 'full page ';
$('rows').innerHTML = cs.length ? cs.map(c => '' + esc(c.name) + ' ' + esc(c.type) + ' #' + c.id + ' · ' + esc(host(c.targetUrl)) + (c.geo ? ' · tiers ' + esc(c.geo) : '') + (c.dailyCap ? ' · cap ' + c.dailyCap + '/day' : '') + '
' + cr(c) + '
' + fmt(c.spent) + ' / ' + fmt(c.budget) + '
' + fmt(c.imps) + (c.impsNas ? '+' + fmt(c.impsNas) + ' network ' : '') + ' ' + fmt(c.clicks) + ' ' + st(c) + ' '
+ (c.status === 'active' ? 'Pause ' : c.status === 'paused' ? 'Resume ' : '')
+ (['active', 'paused', 'out'].includes(c.status) ? 'Top up ' : '') + ' ').join('')
: 'No ads yet. Launch one: a banner, a text ad or the login spot.
';
if (D.gauntletPending) $('earnNote').insertAdjacentHTML('afterend', '');
$('foot').textContent = 'views = timed views in the ad viewer plus member zones; network = the partner ad network · 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')));
$('rows').querySelectorAll('[data-top]').forEach(b => b.addEventListener('click', async () => { const v = await dialog({ title: 'Top up #' + b.dataset.top, text: 'Add credits to this ad. You have ' + fmt(D.availableCredits) + ' available.', fields: [{ k: 'credits', label: 'Credits to add', value: '25', mono: true }], ok: 'Add' }); if (!v) return; try { await api('/api/my/campaigns/' + b.dataset.top + '/topup', { credits: Number(v.credits) }); toast('Topped up.'); load(); } catch (e) { toast(e.message, true); } }));
earnPaint();
}
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/
function earnPaint() {
const s = EARN; if (!s) return;
$('earnBar').style.width = Math.min(100, Math.round(100 * s.views / Math.max(1, s.target))) + '%';
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 = NOTE[t]; $('bannerFields').hidden = t !== 'banner'; $('textFields').hidden = t !== 'text'; $('fCap').parentElement.hidden = t === 'login'; cost(); preview(); }
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 s = 'about ' + Math.floor(b / (r.loginCreditsPerDay || 100)) + ' day' + (Math.floor(b / (r.loginCreditsPerDay || 100)) === 1 ? '' : 's') + ' as the login sponsor (' + (r.loginCreditsPerDay || 100) + ' per day)';
$('fCost').textContent = b >= 10 ? s : 'minimum 10 credits'; }
function preview() { const p = $('prev'); if (TYPE === 'banner' && IMG) { const sz = ($('fSize').value || '728x90').split('x'); p.innerHTML = 'Preview
'; }
else if (TYPE === 'text') p.innerHTML = 'Preview
' + esc($('fTitle').value || 'Your headline') + ' ' + esc($('fBody').value || 'One line under it.') + ' ' + esc(host($('fTarget').value || 'yoursite.com')) + '
';
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 => '' + esc(s.label) + ' ').join('');
try { const r = await CR.get('/api/my/rotations'); SPINS = r.rotations || []; HOSTS = r.hosts || []; $('fSpin').innerHTML = 'pick a spin ' + SPINS.filter(s => !s.paused).map(s => '' + esc(s.name) + ' · /r/' + esc(s.code) + ' ').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 (TYPE === 'banner') { body.size = $('fSize').value; body.imageUrl = $('fImage').value.trim(); }
if (TYPE === 'text') { body.title = $('fTitle').value; body.body = $('fBody').value; }
$('fGo').disabled = true;
try { await api('/api/my/campaigns', body); toast('Launched. It is live in rotation now.'); $('composer').hidden = true; $('fName').value = ''; load(); } catch (e) { toast(e.message, true); } finally { $('fGo').disabled = false; }
});
CR.requireSession(load);
})();