Upstream/public/js/screens/pop.js
jvanvik 249818a7aa Stage 3-5 server (military, expansion, social), web client for stages 1-2, ops/deploy
Built: units/research/training, movements (scan, raid, attack, takeover, reinforce, settle, transport), deterministic
combat resolved in the event queue, reports, power/offline units, founding + conquest + incumbent sites; alliances,
roles, diplomacy (24h pact cancel via events), messages, rankings; vanilla-JS phone-first client (auth, POP, map,
alerts, settings, en/nb); systemd units, backup timer, DEPLOY.md, tools/admin.js.
Tested: npm test 96/96 (fake clock, in-memory db, a few real-HTTP tests); client checked with headless Chromium
screenshots only. NOT done: marketplace/transport trade, client screens for military/social, WebSocket push,
bots/balance, e2e suite. All unit stats and costs are unbalanced first guesses.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Q2MJaQ5LXAHzGnTDgceT14
2026-10-11 18:32:36 +02:00

495 lines
25 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

'use strict';
/*
* POP screen: header, build queue, power, resource fields (grouped by type), infrastructure; tap a building for
* the detail sheet. All numbers come from GET /towns/:id (the server's "next" plan decides what is buildable); the
* client only ticks values forward with rules.js and re-checks affordability live, so a button wakes up the moment
* the resources are there. Countdowns come from the server clock (App.now()).
*/
(function () {
const { h, clear, icon, toast, openSheet, closeSheet } = UI;
const R = UpstreamRules;
const D = UpstreamData;
const F = D.FORMULAS;
let box = null, dirty = true, visible = false;
let refs = { tiles: new Map(), rows: new Map(), queue: [] };
let offTick = null;
let prevQueue = null;
const refetchTries = new Map(); // queue event id -> refetch attempts after it came due
let sheetCtl = null;
const td = () => App.state.townData;
const find = (key) => (td() ? td().buildings.find((b) => b.key === key) : null);
const resOf = (type) => D.FIELD_PRODUCES[type] || null;
// ------------------------------------------------------------------ building state (live)
// 'queued' | 'ready' | 'locked' | 'max' | 'wait'. `code` is the reason it cannot be built now (null = can).
function stateOf(b, cur) {
const t = td();
if (t.queue.some((q) => q.key === b.key)) return { st: 'queued', code: 'already_queued' };
if (b.level >= b.maxLevel) return { st: 'max', code: 'max_level' };
const n = b.next;
let code = n.code;
if (code === 'not_enough_resources' && cur && n.cost) {
let ok = true;
for (const r of D.RESOURCES) if (cur.amounts[r] + 1e-6 < n.cost[r]) ok = false;
if (ok) code = null;
}
if (code === null) return { st: 'ready', code: null };
if (code === 'requirements_not_met') return { st: 'locked', code };
return { st: 'wait', code };
}
// How long until the resources for `cost` are there (ms), or null if never (rate 0) / Infinity if above the storage cap.
function etaFor(cost, cur) {
let worst = 0;
for (const r of D.RESOURCES) {
const need = cost[r] - cur.amounts[r];
if (need <= 0) continue;
if (cost[r] > cur.caps[r]) return Infinity;
const rate = cur.rates[r];
if (rate <= 0) return null;
worst = Math.max(worst, need / rate * D.HOUR_MS);
}
return worst;
}
// ------------------------------------------------------------------ pieces
function costChips(cost, cur, withHave) {
return h('div', { class: 'costs' }, D.RESOURCES.map((r) => {
const short = cur && cur.amounts[r] + 1e-6 < cost[r];
return h('span', { class: 'cost ' + r + (short ? ' short' : ''), dataset: { res: r } }, icon(r),
h('b', { text: App.fmt.num(cost[r]) }),
withHave && cur ? h('small', { text: App.t('sheet.have', { n: App.fmt.num(cur.amounts[r]) }) }) : null);
}));
}
const fmt2 = (x) => x.toFixed(2).replace('.', App.state.lang === 'nb' ? ',' : '.');
function levelPreview(b, toLevel) {
// [{ text }] lines describing what the next level changes, from rules.js.
const t = td(), rt = App.rulesTown(), world = App.state.world;
const lines = [];
const fmt = App.fmt;
const withLevel = (lvl) => {
const bb = Object.assign({}, rt.buildings);
bb[b.key] = { type: b.type, level: lvl };
return Object.assign({}, rt, { buildings: bb });
};
if (b.kind === 'field') {
const res = resOf(b.type);
const mult = res === 'power' ? 1 : (world.speed || 1) * (1 + ((t.bonus && t.bonus[res]) || 0));
const a = R.fieldOutputPerHour(b.level) * mult, c = R.fieldOutputPerHour(toLevel) * mult;
lines.push(App.t('sheet.preview.output', { a: fmt.dec(a), b: fmt.dec(c) }) + ' ' + App.resName(res));
} else if (b.type === 'rack_hall') {
lines.push(App.t('sheet.preview.storage', { a: fmt.num(R.storageCap(withLevel(b.level))), b: fmt.num(R.storageCap(withLevel(toLevel))) }));
} else if (b.type === 'battery_bank') {
lines.push(App.t('sheet.preview.battery', { a: fmt.num(R.batteryCap(withLevel(b.level))), b: fmt.num(R.batteryCap(withLevel(toLevel))) }));
} else if (b.type === 'core_router') {
const k = (l) => fmt2(1 / (1 + F.coreSpeedPerLevel * l));
lines.push(App.t('sheet.preview.core', { a: k(b.level), b: k(toLevel) }));
if (toLevel === F.secondQueueCoreLevel) lines.push(App.t('sheet.preview.core2', { n: toLevel }));
} else if (b.type === 'firewall') {
lines.push(App.t('sheet.preview.firewall', { a: fmt2(1 + F.firewallPerLevel * b.level), b: fmt2(1 + F.firewallPerLevel * toLevel) }));
}
const def = D.BUILDINGS[b.type];
if (def && def.draw > 0) lines.push(App.t('sheet.preview.draw', { n: def.draw }));
return lines;
}
function requirementList(b) {
const def = D.BUILDINGS[b.type];
const levels = {};
for (const x of td().buildings) if (x.kind === 'infra') levels[x.type] = x.level;
return (def.requires || []).map((rq) => {
const have = levels[rq.type] || 0, ok = have >= rq.level;
return h('li', { class: ok ? 'ok' : 'miss' }, icon(ok ? 'check' : 'lock'),
h('span', { text: App.buildingName(rq.type) + ' ' + App.t('pop.level', { n: rq.level }) }),
h('small', { text: App.t('sheet.have', { n: have }) }));
});
}
// ------------------------------------------------------------------ detail sheet
function openBuilding(key, opts) {
const first = find(key);
if (!first) return;
const R_ = { cur: null };
const body = h('div', { class: 'detail' });
const ctl = openSheet({
title: App.buildingName(first.type), icon: 'b-' + first.type, iconClass: first.kind === 'field' ? 'res-' + resOf(first.type) : '',
closeLabel: App.t('common.close'), body,
onClose: () => { if (offSheetTick) offSheetTick(); offSheetTick = null; sheetCtl = null; },
});
sheetCtl = ctl;
let offSheetTick = null;
const els = {};
function build() {
for (const k of Object.keys(els)) delete els[k];
const b = find(key);
if (!b) { ctl.close(); return; }
const cur = App.resourcesNow();
clear(body);
body.appendChild(h('p', { class: 'detail-desc', text: App.buildingDesc(b.type) }));
body.appendChild(h('div', { class: 'detail-level' },
h('span', { class: 'lvl-now', text: b.level > 0 ? App.t('sheet.level', { n: b.level }) : App.t('pop.notBuilt') }),
b.level < b.maxLevel ? h('span', { class: 'lvl-next' }, icon('up'), App.t('sheet.nextLevel', { n: b.level + 1 })) : h('span', { class: 'lvl-next', text: App.t('sheet.maxed') })));
const queued = td().queue.find((q) => q.key === key);
if (queued) {
els.qbar = h('i');
els.qtime = h('b', { class: 'mono' });
body.appendChild(h('div', { class: 'detail-queue' },
h('div', { class: 'row' }, h('span', { text: App.t('sheet.underway') + ' · ' + App.t('pop.queue.to', { n: queued.toLevel }) }), els.qtime),
h('div', { class: 'bar' }, els.qbar)));
els.cancel = h('button', { class: 'btn danger wide', type: 'button', onclick: () => confirmCancel(queued) }, icon('x'), App.t('sheet.cancel'));
body.appendChild(els.cancel);
updateQueueEls(queued, App.now());
return;
}
if (b.level >= b.maxLevel) return;
const to = b.level + 1;
const next = b.next;
for (const text of levelPreview(b, to)) body.appendChild(h('p', { class: 'preview', text }));
els.costs = costChips(next.cost, cur, true);
body.appendChild(h('h3', { class: 'sub', text: App.t('sheet.cost') }));
body.appendChild(els.costs);
body.appendChild(h('div', { class: 'row meta' }, icon('clock'), h('span', { text: App.t('sheet.time') + ': ' }), h('b', { text: App.fmt.dur(next.durationMs) })));
const reqs = requirementList(b);
if (reqs.length) { body.appendChild(h('h3', { class: 'sub', text: App.t('sheet.requires') })); body.appendChild(h('ul', { class: 'reqs' }, reqs)); }
els.reason = h('p', { class: 'reason', 'aria-live': 'polite' });
els.btn = h('button', { class: 'btn primary wide', type: 'button', onclick: () => doBuild(b.key) }, icon('up'), h('span', { text: App.t(b.level > 0 ? 'sheet.upgrade' : 'sheet.build', { n: to }) }));
body.appendChild(els.reason);
body.appendChild(els.btn);
updateLive();
}
function updateQueueEls(q, now) {
const left = q.dueAt - now;
els.qtime.textContent = App.fmt.clock(left);
els.qbar.style.setProperty('--p', String(Math.max(0, Math.min(1, (now - q.startedAt) / Math.max(1, q.dueAt - q.startedAt)))));
}
let busy = false;
function updateLive() {
const b = find(key);
if (!b || !els.btn) return;
const cur = App.resourcesNow();
const s = stateOf(b, cur);
for (const chip of els.costs.children) chip.classList.toggle('short', cur.amounts[chip.dataset.res] + 1e-6 < b.next.cost[chip.dataset.res]);
const can = s.code === null && !busy;
els.btn.disabled = !can;
let reason = '';
if (s.code) {
reason = App.t('err.' + s.code);
if (s.code === 'not_enough_resources') {
const eta = etaFor(b.next.cost, cur);
if (eta === Infinity) reason = App.t('sheet.capTooLow', { cap: App.fmt.num(cur.caps.fiber) });
else if (eta !== null) reason = App.t('sheet.affordableIn', { t: App.fmt.dur(Math.max(1000, eta)) });
}
}
els.reason.textContent = reason;
els.reason.hidden = !reason;
}
async function doBuild(k) {
if (busy) return;
busy = true; els.btn.disabled = true;
els.btn.querySelector('span').textContent = App.t('sheet.building');
const t = td();
try {
const b = find(k);
await App.api.post('/towns/' + t.id + '/build', { key: k }, { intent: 'build:' + t.id + ':' + k });
toast(App.t('sheet.built', { name: App.buildingName(b.type), n: b.level + 1 }), 'ok');
ctl.close();
await App.refreshTown();
} catch (e) {
toast(App.errMsg(e), 'error');
busy = false;
try { await App.refreshTown(); } catch (e2) { /* shown by the offline chip */ }
if (sheetCtl === ctl) build();
}
}
function confirmCancel(q) {
clear(body);
const b = find(key);
body.appendChild(h('p', { class: 'detail-desc', text: App.t('sheet.cancel.confirm', { name: App.buildingName(b.type), n: q.toLevel }) }));
body.appendChild(h('p', { class: 'preview', text: App.t('sheet.cancel.refund') }));
body.appendChild(h('div', { class: 'btn-row' },
h('button', { class: 'btn', type: 'button', onclick: () => build() }, App.t('sheet.cancel.keep')),
h('button', { class: 'btn danger', type: 'button', onclick: async (ev) => {
ev.currentTarget.disabled = true;
try {
await App.api.del('/towns/' + td().id + '/queue/' + q.id);
toast(App.t('sheet.cancelled'), 'ok');
} catch (e) { toast(App.errMsg(e), 'error'); }
ctl.close();
App.refreshTown().catch(() => {});
} }, icon('x'), App.t('sheet.cancel'))));
}
offSheetTick = App.onTick((now) => {
const q = td() && td().queue.find((x) => x.key === key);
if (q && els.qtime) updateQueueEls(q, now); else if (els.btn) updateLive();
});
const offTown = App.on('town', () => { if (sheetCtl === ctl) build(); });
const prevClose = offSheetTick;
offSheetTick = () => { prevClose(); offTown(); };
build();
if (opts && opts.cancel) { const q = td().queue.find((x) => x.key === key); if (q) confirmCancel(q); }
}
// ------------------------------------------------------------------ main drawing
function tileLabel(b, s) {
const status = s.st === 'queued' ? App.t('pop.inQueue') : s.st === 'ready' ? App.t('pop.upgradeReady') : s.st === 'max' ? App.t('pop.max') : s.st === 'locked' ? App.t('pop.locked') : '';
return App.buildingName(b.type) + ', ' + (b.level > 0 ? App.t('pop.level', { n: b.level }) : App.t('pop.notBuilt')) + (status ? ', ' + status : '');
}
function fieldTile(b) {
const res = resOf(b.type);
const lvl = h('b', { class: 'tile-lvl', text: String(b.level) });
const badge = h('span', { class: 'tile-badge', 'aria-hidden': 'true' });
const bar = h('i');
const el = h('button', { class: 'tile res-' + res, type: 'button', dataset: { key: b.key }, onclick: () => openBuilding(b.key) },
icon('b-' + b.type, 'tile-ic'), lvl, badge, h('span', { class: 'tile-bar', 'aria-hidden': 'true' }, bar));
refs.tiles.set(b.key, { el, badge, bar, b });
return el;
}
function infraRow(b) {
const status = h('span', { class: 'pill' });
const sub = h('span', { class: 'row-sub' });
const bar = h('i');
const el = h('button', { class: 'row-btn', type: 'button', dataset: { key: b.key }, onclick: () => openBuilding(b.key) },
h('span', { class: 'row-ic' }, icon('b-' + b.type)),
h('span', { class: 'row-main' },
h('span', { class: 'row-title' }, h('b', { text: App.buildingName(b.type) }), h('span', { class: 'lv', text: b.level > 0 ? App.t('pop.level', { n: b.level }) : App.t('pop.notBuilt') })),
sub),
status, h('span', { class: 'tile-bar', 'aria-hidden': 'true' }, bar));
refs.rows.set(b.key, { el, status, sub, bar, b });
return el;
}
function header(t) {
const st = App.state;
const bonus = D.RESOURCES.filter((r) => (t.bonus && t.bonus[r] > 0)).map((r) => h('span', { class: 'pill res-' + r }, icon(r), '+' + Math.round(t.bonus[r] * 100) + '% ' + App.resName(r)));
const title = st.towns.length > 1
? h('select', { class: 'town-select', 'aria-label': App.t('screen.pop'), onchange: (e) => App.setTown(Number(e.target.value)) },
st.towns.map((x) => h('option', { value: x.id, selected: x.id === t.id, text: x.name })))
: h('h1', { class: 'town-name', text: t.name });
return h('section', { class: 'card pop-head' },
h('div', { class: 'pop-title' }, title,
h('button', { class: 'icon-btn', type: 'button', 'aria-label': App.t('pop.rename'), onclick: openRename }, icon('pencil'))),
h('div', { class: 'pop-meta' },
h('span', { text: App.t('pop.coords', { x: t.x, y: t.y }) }),
t.isCapital ? h('span', { class: 'pill accent', text: App.t('pop.capital') }) : null,
h('span', { class: 'pill' }, icon('shield'), App.t('pop.loyalty') + ' ' + App.fmt.num(t.loyalty)),
h('span', { class: 'pill', text: App.t('pop.footprint') + ' ' + App.fmt.num(t.footprint) + ' (' + App.t('pop.footprintPerDay', { n: App.fmt.num(t.footprintPerDay) }) + ')' }),
bonus.length ? bonus : h('span', { class: 'pill dim', text: App.t('pop.bonus.none') })));
}
function openRename() {
const t = td();
const input = h('input', { type: 'text', value: t.name, maxlength: '40', minlength: '2', 'aria-label': App.t('pop.rename.label'), autocomplete: 'off', enterkeyhint: 'done' });
const err = h('p', { class: 'form-error', role: 'alert', hidden: true });
const save = h('button', { class: 'btn primary wide', type: 'submit' }, icon('check'), App.t('common.save'));
const form = h('form', { class: 'detail', onsubmit: async (ev) => {
ev.preventDefault();
const name = input.value.trim();
if (name.length < 2) { err.textContent = App.t('err.validation_failed'); err.hidden = false; return; }
save.disabled = true;
try {
const r = await App.api.post('/towns/' + t.id + '/rename', { name });
const known = App.state.towns.find((x) => x.id === t.id);
if (known) known.name = r.name;
toast(App.t('pop.rename.done'), 'ok');
sheet.close();
await App.refreshTown();
} catch (e) { err.textContent = App.errMsg(e); err.hidden = false; save.disabled = false; }
} }, h('label', { class: 'field' }, h('span', { class: 'field-lbl', text: App.t('pop.rename.label') }), input), err, save);
const sheet = openSheet({ title: App.t('pop.rename'), icon: 'pencil', closeLabel: App.t('common.close'), body: form });
setTimeout(() => { input.focus(); input.select(); }, 60);
}
function queueCard(t) {
refs.queue = [];
const slots = h('span', { class: 'pill', text: App.t('pop.queue.slots', { used: t.queue.length, total: t.queueSlots }) });
const list = h('div', { class: 'queue' });
for (const q of t.queue) {
const time = h('b', { class: 'mono' }), bar = h('i');
const name = App.buildingName(q.type);
list.appendChild(h('div', { class: 'q-item' },
h('button', { class: 'q-main', type: 'button', onclick: () => openBuilding(q.key), 'aria-label': name + ' ' + App.t('pop.queue.to', { n: q.toLevel }) },
h('span', { class: 'row-ic' }, icon('b-' + q.type)),
h('span', { class: 'row-main' }, h('span', { class: 'row-title' }, h('b', { text: name }), h('span', { class: 'lv', text: App.t('pop.queue.to', { n: q.toLevel }) })),
h('span', { class: 'bar' }, bar)),
time),
h('button', { class: 'icon-btn', type: 'button', 'aria-label': App.t('pop.queue.cancel') + ': ' + name, onclick: () => openBuilding(q.key, { cancel: true }) }, icon('x'))));
refs.queue.push({ q, time, bar });
}
if (!t.queue.length) list.appendChild(h('p', { class: 'empty', text: App.t('pop.queue.empty') }));
return h('section', { class: 'card' }, h('div', { class: 'card-head' }, h('h2', { text: App.t('pop.queue.title') }), slots), list);
}
function powerCard() {
refs.power = { out: h('b'), draw: h('b'), net: h('b'), buf: h('span', { class: 'mono' }), bar: h('i'), status: h('p', { class: 'power-status' }) };
const p = refs.power;
return h('section', { class: 'card power-card' },
h('div', { class: 'card-head' }, h('h2', null, icon('power'), App.t('power.title'))),
h('div', { class: 'stat-row' },
h('div', { class: 'stat' }, h('small', { text: App.t('power.out') }), p.out),
h('div', { class: 'stat' }, h('small', { text: App.t('power.draw') }), p.draw),
h('div', { class: 'stat' }, h('small', { text: App.t('power.net') }), p.net)),
h('div', { class: 'row' }, h('span', { class: 'dimmer', text: App.t('power.buffer') }), p.buf),
h('div', { class: 'bar power-bar', 'aria-hidden': 'true' }, p.bar), p.status);
}
function fieldsCard(t) {
const fields = t.buildings.filter((b) => b.kind === 'field');
const world = App.state.world;
const groups = h('div', { class: 'groups' });
for (const type of D.FIELD_TYPES) {
const list = fields.filter((b) => b.type === type);
if (!list.length) continue;
const res = resOf(type);
const mult = res === 'power' ? 1 : (world.speed || 1) * (1 + ((t.bonus && t.bonus[res]) || 0));
const total = list.reduce((s, b) => s + R.fieldOutputPerHour(b.level) * mult, 0);
groups.appendChild(h('div', { class: 'group res-' + res },
h('div', { class: 'group-head' }, icon(res), h('b', { text: App.buildingName(type) }), h('span', { class: 'dimmer', text: '×' + list.length }),
h('span', { class: 'group-rate', text: App.fmt.dec(total, true) + ' ' + App.resName(res) + App.t('common.perHour') })),
h('div', { class: 'tiles' }, list.map(fieldTile))));
}
return h('section', { class: 'card' }, h('div', { class: 'card-head' }, h('h2', { text: App.t('pop.fields.title') })), groups);
}
function infraCard(t) {
const list = t.buildings.filter((b) => b.kind === 'infra');
return h('section', { class: 'card' }, h('div', { class: 'card-head' }, h('h2', { text: App.t('pop.infra.title') })), h('div', { class: 'rows' }, list.map(infraRow)));
}
function draw() {
dirty = false;
refs = { tiles: new Map(), rows: new Map(), queue: [] };
clear(box);
const t = td();
if (!App.state.townId) { box.appendChild(h('p', { class: 'empty pad', text: App.t('pop.noTown') })); return; }
if (!t) { box.appendChild(h('div', { class: 'boot' }, h('div', { class: 'spinner', 'aria-hidden': 'true' }), h('p', { text: App.t('common.loading') }))); return; }
box.appendChild(h('div', { class: 'cols' },
h('div', { class: 'col' }, header(t), queueCard(t), powerCard()),
h('div', { class: 'col' }, fieldsCard(t), infraCard(t))));
tick(App.now());
}
// ------------------------------------------------------------------ ticking
function tick(now) {
const t = td();
if (!t || !refs.power) return;
const cur = App.resourcesNow(now);
const f = App.fmt;
// queue countdowns + the refetch when something comes due
for (const e of refs.queue) {
const q = e.q, left = q.dueAt - now;
const time = f.clock(left);
if (e.time.textContent !== time) e.time.textContent = time;
e.bar.style.setProperty('--p', String(Math.max(0, Math.min(1, (now - q.startedAt) / Math.max(1, q.dueAt - q.startedAt)))));
if (left <= -300) {
const tries = refetchTries.get(q.id) || { n: 0, at: 0 };
if (Date.now() >= tries.at) {
refetchTries.set(q.id, { n: tries.n + 1, at: Date.now() + Math.min(10000, 1500 * (tries.n + 1)) });
App.refreshTown().catch(() => {});
}
}
}
// tiles and rows
const queueByKey = new Map(t.queue.map((q) => [q.key, q]));
for (const [key, e] of refs.tiles) {
const s = stateOf(e.b, cur);
if (e.el.dataset.st !== s.st) {
e.el.dataset.st = s.st;
e.badge.textContent = '';
if (s.st === 'queued') e.badge.appendChild(icon('clock'));
else if (s.st === 'ready') e.badge.appendChild(icon('up'));
else if (s.st === 'locked') e.badge.appendChild(icon('lock'));
e.el.setAttribute('aria-label', tileLabel(e.b, s));
}
const q = queueByKey.get(key);
e.bar.style.setProperty('--p', q ? String(Math.max(0, Math.min(1, (now - q.startedAt) / Math.max(1, q.dueAt - q.startedAt)))) : '0');
}
for (const [key, e] of refs.rows) {
const s = stateOf(e.b, cur);
const q = queueByKey.get(key);
let pill = '', pillCls = 'pill', sub = '';
if (s.st === 'queued') { pill = f.clock(q.dueAt - now); pillCls += ' amber mono'; sub = App.buildingDesc(e.b.type); }
else if (s.st === 'ready') { pill = App.t(e.b.level > 0 ? 'pop.upgradeReady' : 'sheet.build', { n: e.b.level + 1 }); pillCls += ' green'; sub = App.buildingDesc(e.b.type); }
else if (s.st === 'max') { pill = App.t('pop.max'); sub = App.buildingDesc(e.b.type); }
else if (s.st === 'locked') {
const m = (e.b.next.missing || [])[0];
pill = m ? App.buildingName(m.type) + ' ' + App.t('pop.level', { n: m.level }) : App.t('pop.locked'); pillCls += ' dim';
sub = App.buildingDesc(e.b.type);
} else sub = App.buildingDesc(e.b.type);
if (e.status.textContent !== pill) e.status.textContent = pill;
e.status.className = pillCls;
e.status.hidden = !pill;
if (e.sub.textContent !== sub) e.sub.textContent = sub;
e.el.dataset.st = s.st;
e.bar.style.setProperty('--p', q ? String(Math.max(0, Math.min(1, (now - q.startedAt) / Math.max(1, q.dueAt - q.startedAt)))) : '0');
}
// power
const p = refs.power, net = cur.rates.powerNet, buf = cur.amounts.battery, bcap = cur.caps.battery;
p.out.textContent = f.dec(cur.rates.powerOut);
p.draw.textContent = f.dec(cur.rates.powerDraw);
p.net.textContent = f.dec(net, true);
p.net.className = net < 0 ? 'bad' : 'good';
p.buf.textContent = f.num(buf) + ' / ' + f.num(bcap) + ' ' + App.t('power.unit');
p.bar.style.setProperty('--p', String(bcap > 0 ? Math.min(1, buf / bcap) : 0));
const speed = App.state.world.speed || 1;
let status, cls = '';
if (net < 0) {
if (buf <= 0) { status = App.t('power.empty'); cls = 'bad'; }
else { status = App.t('power.draining', { t: f.dur(buf / (-net * speed) * D.HOUR_MS) }); cls = 'warn'; }
} else if (net > 0 && buf < bcap - 0.01) status = App.t('power.charging', { t: f.dur((bcap - buf) / (net * speed) * D.HOUR_MS) });
else status = buf >= bcap - 0.01 && bcap > 0 ? App.t('power.full') : App.t('power.ok');
if (p.status.textContent !== status) p.status.textContent = status;
p.status.className = 'power-status ' + cls;
}
// ------------------------------------------------------------------ town changed
function onTown(t) {
// toast for levels that finished since the last fetch
if (prevQueue && prevQueue.townId === t.id) {
const nowIds = new Set(t.queue.map((q) => q.id));
for (const q of prevQueue.items) {
if (nowIds.has(q.id)) continue;
const b = t.buildings.find((x) => x.key === q.key);
if (b && b.level >= q.toLevel) toast(App.t('alerts.build_done', { name: App.buildingName(q.type), level: b.level }), 'ok');
refetchTries.delete(q.id);
App.checkAlerts();
}
}
prevQueue = { townId: t.id, items: t.queue.slice() };
if (visible) draw(); else dirty = true;
}
App.registerScreen({
id: 'pop', titleKey: 'screen.pop', navKey: 'nav.pop', icon: 'pop', hud: true,
render(container) {
box = container;
App.on('town', onTown);
App.on('session', () => { dirty = true; prevQueue = null; });
App.on('townchange', () => { dirty = true; if (visible) draw(); });
},
onShow() {
visible = true;
draw();
if (offTick) offTick();
offTick = App.onTick(tick);
if (td() && Date.now() - App.state.townFetchedAt > 15000) App.refreshTown().catch(() => {});
},
onHide() { visible = false; if (offTick) offTick(); offTick = null; closeSheet(); },
});
}());