// LinkSpin Links workspace (Control Room, first real screen, 2026-09-29). Talks to the existing rotator API:
// GET /api/my/rotations, POST /api/my/rotations, POST /api/my/rotations/:id, POST .../dest, POST .../dest/:did, GET .../stats
(function () {
const $ = id => document.getElementById(id);
const esc = s => String(s == null ? '' : s).replace(/[&<>"]/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"' }[c]));
const fmt = n => Number(n || 0).toLocaleString();
let ROT = [], HOSTS = [], SEL = null, STATS = {}, FILTER = '';
let toastT;
function toast(msg, bad) { const t = $('toast'); t.textContent = msg; t.style.background = bad ? '#FF7A7A' : ''; t.classList.add('on'); clearTimeout(toastT); toastT = setTimeout(() => t.classList.remove('on'), 1800); }
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 copy(text) { try { navigator.clipboard.writeText(text).then(() => toast('Copied'), () => toast('Select and copy: ' + text)); } catch (e) { toast('Select and copy: ' + text); } }
// in-page dialogs (never native prompt/confirm)
function dialog(opts) {
return new Promise(resolve => {
const host = $('modalHost'); host.innerHTML = '';
const back = document.createElement('div'); back.className = 'modal-back';
back.innerHTML = '
' + esc(opts.title) + '
' + (opts.text ? '
' + esc(opts.text) + '
' : '')
+ (opts.fields || []).map(f => '
').join('')
+ '
';
host.appendChild(back);
const done = v => { host.innerHTML = ''; resolve(v); };
back.querySelector('#dlgNo').addEventListener('click', () => done(null));
back.addEventListener('click', e => { if (e.target === back) done(null); });
back.querySelector('#dlgOk').addEventListener('click', () => { const out = {}; (opts.fields || []).forEach(f => { out[f.k] = back.querySelector('#dlg-' + f.k).value; }); done(opts.fields ? out : true); });
const first = back.querySelector('input'); if (first) { first.focus(); first.select(); back.addEventListener('keydown', e => { if (e.key === 'Enter') back.querySelector('#dlgOk').click(); if (e.key === 'Escape') done(null); }); }
});
}
const linkUrl = r => 'https://' + (HOSTS[0] || location.host) + '/r/' + r.code;
const clicks7 = r => r.hits7 || 0;
const health = r => r.paused ? { cls: 'warn', t: 'PAUSED' } : !r.destinations.some(d => d.active) ? { cls: 'bad', t: 'NO LIVE DESTINATION' } : { cls: 'ok', t: 'LIVE' };
async function load(keep) {
let r; try { r = await (await fetch('/api/my/rotations', { headers: { Accept: 'application/json' } })).json(); } catch (e) { r = { error: 'network' }; }
if (r.error) { $('signin').hidden = false; $('ws').hidden = true; $('tbSub').textContent = 'not signed in'; return; }
ROT = (r.rotations || []).slice().sort((a, b) => clicks7(b) - clicks7(a)); HOSTS = r.hosts || [];
$('signin').hidden = true; $('ws').hidden = false;
const tot7 = ROT.reduce((n, x) => n + clicks7(x), 0);
$('tbSub').textContent = ROT.length + ' link' + (ROT.length === 1 ? '' : 's') + ' · ' + fmt(tot7) + ' clicks in 7 days';
renderList();
if (keep && SEL != null) { const s = ROT.find(x => x.id === SEL); if (s) return select(s.id, true); }
if (!ROT.length) { $('noSel').hidden = false; $('sel').hidden = true; SEL = null; }
else if (SEL == null) select(ROT[0].id, true);
}
function renderList() {
const q = FILTER.trim().toLowerCase();
const rows = ROT.filter(x => !q || x.name.toLowerCase().includes(q) || x.code.includes(q));
$('listCount').textContent = ROT.length + ' link' + (ROT.length === 1 ? '' : 's');
$('items').innerHTML = rows.length ? rows.map(x => { const h = health(x); return ''
+ '
' + esc(x.name) + (h.cls !== 'ok' ? ' ' + h.t + '' : '') + '
' + esc((HOSTS[0] || location.host) + '/r/' + x.code) + '
'
+ '
' + fmt(clicks7(x)) + '7 d
'; }).join('')
: '' + (ROT.length ? 'No link matches that filter.' : 'No links yet.') + '
';
$('items').querySelectorAll('.item').forEach(el => { const go = () => select(Number(el.dataset.id)); el.addEventListener('click', go); el.addEventListener('keydown', e => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); go(); } }); });
}
async function select(id, quiet) {
SEL = id; const r = ROT.find(x => x.id === id); if (!r) return;
$('noSel').hidden = true; $('sel').hidden = false; $('ws').classList.add('focus');
$('items').querySelectorAll('.item').forEach(el => el.classList.toggle('on', Number(el.dataset.id) === id));
$('dName').textContent = r.name; $('dUrl').textContent = linkUrl(r);
const h = health(r); $('dLive').innerHTML = '' + h.t + '';
$('pauseBtn').textContent = r.paused ? 'Resume' : 'Pause';
$('fallback').value = r.fallback || '';
const bots = r.bots || 0;
$('tiles').innerHTML = [['Served, 7 d', fmt(r.hits7 || 0)], ['Unique, all time', fmt(r.uniques || 0)], ['Clicks, all time', fmt(r.hits || 0)], ['Bots dropped', fmt(bots)], ['Live destinations', r.destinations.filter(d => d.active).length + ' / ' + r.destinations.length]]
.map(([k, v], i) => '' + k + '' + v + '
').join('');
renderDest(r);
if (!quiet) window.scrollTo({ top: 0 });
loadStats(r.id);
}
function renderDest(r) {
const total = r.destinations.filter(d => d.active).reduce((n, d) => n + d.weight, 0) || 1;
$('destRows').innerHTML = r.destinations.length ? r.destinations.map(d => { const share = d.active ? Math.round(d.weight / total * 100) : 0;
return '' + esc(d.label || d.url.replace(/^https?:\/\//, '').slice(0, 60)) + '
' + esc(d.url) + '
'
+ '
'
+ '
' + fmt(d.hits || 0) + '' + fmt(d.uniques || 0) + ''
+ '
' + (d.active ? 'LIVE' : 'PAUSED') + ''
+ '
'; }).join('')
: 'No destinations yet. Add the first page below; until then the link sends people to the fallback.
';
$('destFoot').textContent = 'weights are shares of the spin · fallback: ' + (r.fallback || 'none set') + ' · bots filtered on the server · one hop';
$('destRows').querySelectorAll('[data-w]').forEach(i => i.addEventListener('change', async () => { try { await api('/api/my/rotations/' + r.id + '/dest/' + i.dataset.w, { weight: i.value }); toast('Weight saved'); load(true); } catch (e) { toast(e.message, true); } }));
$('destRows').querySelectorAll('[data-t]').forEach(b => b.addEventListener('click', async () => { const d = r.destinations.find(q => q.id === Number(b.dataset.t)); try { await api('/api/my/rotations/' + r.id + '/dest/' + d.id, { active: !d.active }); load(true); } catch (e) { toast(e.message, true); } }));
$('destRows').querySelectorAll('[data-x]').forEach(b => b.addEventListener('click', async () => { if (!await dialog({ title: 'Remove this destination?', text: 'Its click history stays in the stats.', ok: 'Remove', danger: true })) return; try { await api('/api/my/rotations/' + r.id + '/dest/' + b.dataset.x, { remove: true }); toast('Removed'); load(true); } catch (e) { toast(e.message, true); } }));
}
async function loadStats(id) {
let s = STATS[id]; if (!s) { try { s = await (await fetch('/api/my/rotations/' + id + '/stats')).json(); } catch (e) { s = null; } if (!s || s.error) return; STATS[id] = s; setTimeout(() => { delete STATS[id]; }, 60000); }
if (SEL !== id) return;
const hmax = Math.max(1, ...s.hours); $('hourBars').innerHTML = s.hours.map((n, i) => '').join('');
const kv = rows => rows.length ? rows.map(x => '' + esc(x.k) + '' + fmt(x.n) + '').join('') : 'nothing yet';
$('srcRows').innerHTML = kv(s.source); $('geoRows').innerHTML = kv(s.country);
const dev = s.device || []; const dt = dev.reduce((n, x) => n + x.n, 0) || 1; $('devRow').textContent = dev.length ? dev.map(x => x.k + ' ' + Math.round(x.n / dt * 100) + '%').join(' · ') : '';
const days = s.days || []; const dmax = Math.max(1, ...days.map(d => d.n));
$('dayBars').style.gridTemplateColumns = 'repeat(' + Math.max(1, days.length) + ',minmax(0,1fr))';
$('dayBars').innerHTML = days.length ? days.map(d => '').join('') : '';
$('dayAxis').innerHTML = days.length ? '' + days[0].day + '' + days[days.length - 1].day + '' : 'no clicks recorded yet';
}
// actions
async function newSpin() {
const v = await dialog({ title: 'New spin', text: 'Name it for you, not for visitors. You add the pages next.', fields: [{ k: 'name', label: 'Name', placeholder: 'IAP main invite', max: 80 }, { k: 'url', label: 'First page to send people to (optional)', placeholder: 'https://', mono: true, type: 'url' }], ok: 'Create' });
if (!v || !v.name.trim()) return;
try { const r = await api('/api/my/rotations', { name: v.name }); const id = r.rotation.id; if (v.url && v.url.trim()) await api('/api/my/rotations/' + id + '/dest', { url: v.url.trim(), weight: 10 }); SEL = id; toast('Link created'); await load(true); } catch (e) { toast(e.message, true); }
}
$('newBtn').addEventListener('click', newSpin); $('newBtn2').addEventListener('click', newSpin);
$('filter').addEventListener('input', e => { FILTER = e.target.value; renderList(); });
$('copyBtn').addEventListener('click', () => { const r = ROT.find(x => x.id === SEL); if (r) copy(linkUrl(r)); });
$('backBtn').addEventListener('click', () => { $('ws').classList.remove('focus'); });
$('renameBtn').addEventListener('click', async () => { const r = ROT.find(x => x.id === SEL); if (!r) return; const v = await dialog({ title: 'Rename', fields: [{ k: 'name', label: 'Name', value: r.name, max: 80 }], ok: 'Save' }); if (!v || !v.name.trim()) return; try { await api('/api/my/rotations/' + r.id, { name: v.name }); load(true); } catch (e) { toast(e.message, true); } });
$('pauseBtn').addEventListener('click', async () => { const r = ROT.find(x => x.id === SEL); if (!r) return; try { await api('/api/my/rotations/' + r.id, { paused: !r.paused }); toast(r.paused ? 'Live again' : 'Paused: visitors go to the fallback'); load(true); } catch (e) { toast(e.message, true); } });
$('delBtn').addEventListener('click', async () => { const r = ROT.find(x => x.id === SEL); if (!r) return; if (!await dialog({ title: 'Delete ' + r.name + '?', text: 'The short link stops working for everyone who has it. This cannot be undone.', ok: 'Delete', danger: true })) return; try { await api('/api/my/rotations/' + r.id, { remove: true }); SEL = null; toast('Deleted'); load(); } catch (e) { toast(e.message, true); } });
$('addBtn').addEventListener('click', async () => { const r = ROT.find(x => x.id === SEL); if (!r) return; const url = $('addUrl').value.trim(); if (!url) { $('addUrl').focus(); return; } try { await api('/api/my/rotations/' + r.id + '/dest', { url, label: $('addLabel').value, weight: $('addWeight').value }); $('addUrl').value = ''; $('addLabel').value = ''; toast('Destination added'); load(true); } catch (e) { toast(e.message, true); } });
$('addUrl').addEventListener('keydown', e => { if (e.key === 'Enter') $('addBtn').click(); });
$('fallback').addEventListener('change', async () => { const r = ROT.find(x => x.id === SEL); if (!r) return; try { await api('/api/my/rotations/' + r.id, { fallback: $('fallback').value.trim() }); toast('Fallback saved'); load(true); } catch (e) { toast(e.message, true); } });
$('tabs').querySelectorAll('button').forEach(b => b.addEventListener('click', () => { $('tabs').querySelectorAll('button').forEach(x => x.classList.toggle('on', x === b)); ['dest', 'hours', 'sources', 'report'].forEach(t => { $('tab-' + t).hidden = t !== b.dataset.tab; }); }));
$('backBtn').hidden = !window.matchMedia('(max-width:760px)').matches;
load();
setInterval(() => { if (!document.hidden) load(true); }, 60000);
})();