// LinkSpin Control Room shell (2026-09-29): the frame every workspace screen shares.
// Rail + topbar, session check, in-shell sign-in (email code, same endpoints as the dashboard),
// fetch helper, toast, in-page dialogs (never native prompt/confirm). Pages: put content in
//
, then CR.mount({active,title,sub,actions}) and CR.requireSession(cb).
window.CR = (function () {
const $ = id => document.getElementById(id);
const esc = s => String(s == null ? '' : s).replace(/[&<>"]/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"' }[c]));
const fmt = n => Number(n || 0).toLocaleString();
const NAV = [
['links', 'Links', '/links', ''],
['sources', 'Sources', '/sources', ''],
['pages', 'Pages', '/pages', ''],
['zones', 'Zones', '/zones', ''],
['ads', 'Ads', '/ads', ''],
['credits', 'Credits', '/credits', ''],
['refuel', 'Refuel', '/credits#refuel', ''], // Monthly Refuel panel on Credits (Marty 2026-10-25: no refuel option in the menu)
['reports', 'Reports', '/reports', ''],
['conversions', 'Conversions', '/conversions', ''], // conversion pixel goals (2026-10-23)
['team', 'Team', '/team', ''],
['wallet', 'Wallet', '/wallet', ''],
['promo', 'Promo tools', '/tools#promo', ''],
['training', 'Training', '/tools#training', '', 1],
['pipeline', 'Pipeline', '/tools#pipeline', '', 1],
['profile', 'Profile', '/tools#profile', '', 1],
['help', 'Help', '/help', ''],
['tools', 'More', '/tools', ''],
];
// screens not built yet fall back to the classic dashboard pane so nothing is a dead end
const FALLBACK = {}; // the classic /my dashboard is retired (2026-10-08); its leftover panes live at /tools
const BUILT = new Set(['links', 'sources', 'pages', 'zones', 'ads', 'credits', 'refuel', 'reports', 'conversions', 'team', 'wallet', 'tools', 'promo', 'training', 'pipeline', 'profile', 'help']); // Training, Pipeline and Profile on the rail, not behind More (Marty 2026-10-11); Help = support tickets (2026-10-16)
let ME = null, toastT;
// Deep links (2026-10-25): /credits#refuel, /credits#buy and /ads#engine scroll to their panel once it has loaded (and any
// sign-in or sponsor pop-up is closed) and flash it, so a button that says "Refuel" lands ON the Refuel panel.
const ANCHOR = { refuel: 'rfPanel', buy: 'buyPanel', engine: 'erPanel', kit: 'rkPanel' };
function focusAnchor() {
const id = ANCHOR[location.hash.slice(1)]; if (!id) return;
const t0 = Date.now();
const tick = () => {
const el = $(id);
if (!el || el.hidden || !el.offsetParent || document.querySelector('.modal-back')) { if (Date.now() - t0 < 90000) setTimeout(tick, 400); return; }
el.scrollIntoView({ behavior: 'smooth', block: 'start' });
el.classList.remove('cr-flash'); void el.offsetWidth; el.classList.add('cr-flash');
// panels above it (packages, purchases) can still be loading and push it down, mostly on phones: settle once more
setTimeout(() => { const r = el.getBoundingClientRect(); if (Math.abs(r.top) > 60) el.scrollIntoView({ block: 'start' }); }, 1600);
};
setTimeout(tick, 200);
}
// Arrival strip (2026-10-25, Marty: "it took me to LinkSpin, but I really don't know how to pick up from there"): a link from
// InstantAdPay carries ?from=iap&task=; the screen opens with one line naming the job, its first step, a guide and the way back.
const ARRIVE = {
refuel: ['refuel LinkSpin', 'pick a package of $25 or more (marked "counts for Refuel") under Buy a package, then press Buy. It counts toward the same streak as InstantAdPay.', '/refuel', 'How the Refuel streak works'],
conversions: ['set up conversion tracking', 'press Add a goal and name it, for example subscriber or sale. Then paste its two snippets on your pages.', '/conversion-tracking', 'Step-by-step setup guide'],
bannerspin: ['make a Banner Spin', 'press + New Banner Spin, pick a banner size and add up to 5 banners. LinkSpin keeps showing the one that gets clicked.'],
spinlink: ['make a spin link', 'press + New spin and paste the page you promote. You get one short link to use in your ads.'],
testing: ['test A against B', 'open your spin link and add a second page under Destinations (or a second banner to a Banner Spin). The rotation picks the winner.'],
page: ['build a page', 'press + New page, fill it in and publish it. Then add it to a spin link.'],
ads: ['check your LinkSpin ads', 'your LinkSpin ads are listed on this screen. Open the one you came for to top it up or relaunch it.'],
};
const qp = (() => { try { return new URLSearchParams(location.search); } catch (e) { return new URLSearchParams(''); } })();
const ARR = qp.get('from') === 'iap' ? (ARRIVE[qp.get('task')] || ['carry on from InstantAdPay', 'use the menu on the left. Everything here signs in with the same email.']) : null;
function arriveStrip() {
if (!ARR || $('crArrive')) return '';
if (!document.getElementById('crArriveCss')) { const st = document.createElement('style'); st.id = 'crArriveCss'; st.textContent = '.arrive{display:flex;flex-wrap:wrap;gap:6px 14px;align-items:center;margin:12px 24px 0;padding:10px 14px;border:1px solid var(--sig,#ff6a1a);border-radius:8px;background:var(--sig-soft,#FFF8F2);font-size:13.5px;line-height:1.45}.arrive .grow{flex:1 1 auto}.arrive button{border:0;background:none;font-size:18px;line-height:1;cursor:pointer;color:inherit;padding:0 2px}@media (max-width:900px){.arrive{margin:10px 16px 0}}.cr-flash{animation:crFlash 2.4s ease-out 1}@keyframes crFlash{0%,40%{box-shadow:0 0 0 4px rgba(255,106,26,.55)}100%{box-shadow:0 0 0 0 rgba(255,106,26,0)}}'; document.head.appendChild(st); }
return '
You came from InstantAdPay to ' + esc(ARR[0]) + '.Sign in with the same email you use on InstantAdPay, then Step 1: ' + esc(ARR[1])
+ (ARR[2] ? ' ' + esc(ARR[3]) + '' : '') + 'Back to InstantAdPay
';
}
// Expired session (Marty 2026-10-23: "told me to sign in but never redirected me"): sessions last 24 h, and a screen
// left open past that got 'Sign in first.' errors with no way forward. Any 401 from our API, or coming back to a tab
// whose session has lapsed, opens the in-shell sign-in once and reloads the screen after it.
let lostOpen = false, lastCheck = Date.now();
function sessionLost() { if (lostOpen) return; lostOpen = true; ME = null; toast('Your session ended. Sign in again to keep going.', true); signInFlow(() => location.reload()); }
(function () { const f0 = window.fetch.bind(window); window.fetch = async function (input, init) { const r = await f0(input, init); try { const u = new URL(typeof input === 'string' ? input : input.url, location.href); if (r.status === 401 && u.origin === location.origin && /^\/api\//.test(u.pathname) && !/^\/api\/(auth|me$)/.test(u.pathname) && !/^\/api\/admin\//.test(u.pathname)) sessionLost(); } catch (e) {} return r; }; })();
document.addEventListener('visibilitychange', async () => { if (document.visibilityState !== 'visible' || lostOpen || !ME || !ME.signedIn || Date.now() - lastCheck < 60000) return; lastCheck = Date.now(); const m = await me(true); if (!m || !m.signedIn) sessionLost(); });
function toast(msg, bad) { let t = $('crToast'); if (!t) { t = document.createElement('div'); t.id = 'crToast'; t.className = 'toast'; t.setAttribute('role', 'status'); document.body.appendChild(t); } t.textContent = msg; t.classList.toggle('bad', !!bad); t.classList.add('on'); clearTimeout(toastT); toastT = setTimeout(() => t.classList.remove('on'), 2000); }
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; }
async function get(path) { const r = await (await fetch(path, { headers: { Accept: 'application/json' } })).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); } }
function dialog(opts) {
return new Promise(resolve => {
let host = $('crModalHost'); if (!host) { host = document.createElement('div'); host.id = 'crModalHost'; document.body.appendChild(host); }
host.innerHTML = '';
const back = document.createElement('div'); back.className = 'modal-back';
back.innerHTML = '