%#
Shared statistics body for the admin Stats page (views/stats.ejs) and the public page (views/public_stats.ejs).
Two views (?v=community | streams) x periods (?p=stream|week|month|year|all).
Community: supporters, raids, leaderboards, community ranks, emotes, commands, rewards.
Streams: numbers, one activity chart (pick what to show), games played, the streams list; one stream: viewer graph.
Locals: s = periodstats.summary(), q = rangeQuery helper, base = link prefix ('/stats', '/public' or '/'),
view = 'community' | 'streams', mode = 'admin' | 'public', viewerHref = viewer link prefix or null,
extraBoards = [{ title, rows, level, wide }], ranks = [{ login, name, level }] (Regular and up, all time).
Colours come from the page: --muted, --line, --accent, --accent-hover, --card (and --card-solid for popups).
A new section goes here once and appears on both pages; wrap it in `if (admin)` when it is not for the public.
%>
<%
const admin = locals.mode === 'admin';
const esc = v => String(v ?? '').replace(/[&<>"]/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"' }[c]));
const num = n => Number(n || 0).toLocaleString('en-US');
const hm = m => m >= 60 ? `${Math.floor(m / 60)} h ${String(Math.round(m % 60)).padStart(2, '0')} m` : `${Math.round(m)} m`;
const r = s.range, T = s.totals, C = s.channel || {}, TW = s.twitch;
const v = locals.view === 'streams' ? 'streams' : 'community';
const cur = { p: r.p, d: r.from || undefined, s: r.p === 'stream' ? r.stream.id : undefined };
const link = (rq, view = v) => base + q({ ...rq, v: view === 'community' ? undefined : view });
const TZ = locals.tz || 'UTC'; // Settings → General → Time zone
const day = iso => new Date(iso).toLocaleDateString('en-GB', { day: 'numeric', month: 'short', year: 'numeric', timeZone: TZ });
const time = iso => new Date(iso).toLocaleTimeString('en-GB', { hour: '2-digit', minute: '2-digit', timeZone: TZ });
const emoteSrc = e => e.source === 'twitch' && e.id ? `https://static-cdn.jtvnw.net/emoticons/v2/${e.id}/default/dark/1.0`
: e.source === '7tv' && e.id ? `https://cdn.7tv.app/emote/${e.id}/1x.webp` : null;
// ⓘ with an instant tooltip (hover, or tap / keyboard focus)
const info = text => text ? ` ⓘ` : '';
const person = x => { const n = esc(x.name || x.login || '?'); return viewerHref && x.login ? `${n}` : n; };
const since = TW && TW.streamedDays ? TW.cutoff : null; // period reaches back before HeyStreamer counted
%>
<%
// ---- number tiles. Public: a short, friendly set; admin: everything ----
const T_ = {}; // id -> [value, label, tooltip]
T_.messages = [num(T.messages), 'chat messages', since ? `Before ${since} from Twitch's daily analytics, after that counted by HeyStreamer` : ''];
T_.watch = [num(T.watchHours), 'hours watched', T.historyWatchHours ? `${num(T.historyWatchHours)} h from Twitch's daily analytics (before ${since}), the rest counted by HeyStreamer` : T.baselineHours ? `Includes ${num(T.baselineHours)} h counted by StreamElements before HeyStreamer counted itself` : ''];
if (r.p !== 'stream') T_.streams = [num(T.streams), T.streams === 1 ? 'stream' : 'streams', since ? `Before ${since} every day with a stream counts as one stream (Twitch's daily analytics)` : ''];
T_.streamed = r.p === 'stream' && s.streams[0] ? [hm(s.streams[0].minutes), s.streams[0].live ? 'live for' : 'streamed'] : [num(T.hoursStreamed), 'hours streamed'];
T_.emotes = [num(T.emotes), 'emotes used', since ? `Counted by HeyStreamer since ${since}` : ''];
if (TW && TW.clips) T_.clips = [num(TW.clips), 'clips created', `${num(TW.clipViews)} clip views (Twitch's daily analytics)`];
T_.redeems = [num(T.redeems), 'rewards redeemed', `${num(T.channelPoints)} channel points spent${since ? `; counted since ${since}` : ''}`];
if (admin) {
if (r.p === 'all' && C.followers != null) T_.followers = [num(C.followers), 'followers', 'Following the channel right now (from Twitch)'];
if (r.p === 'all' && C.subsNow != null) T_.subsNow = [num(C.subsNow), 'subscribers', 'Subscribed right now (from Twitch, without the streamer)'];
T_.chatters = [num(T.chatters), since ? `chatters since ${since}` : 'chatters', 'Different people who chatted. Twitch\'s export has no names, so this only counts from HeyStreamer\'s start'];
T_.viewers = [num(T.viewers), since ? `viewers since ${since}` : 'viewers', `Different people in the chatter list while live, lurkers included${T.viewersFromBaseline ? `. Includes ${num(T.viewersFromBaseline)} viewers known only from StreamElements' watch time (from before HeyStreamer counted), which is why All time is higher than the other tabs` : ''}`];
const pk = r.p === 'stream' ? s.streams[0] : C;
if (pk && pk.peak != null) T_.peak = [num(pk.peak), 'peak viewers', pk.avg != null ? `About ${num(pk.avg)} on average` : ''];
if (TW && TW.uniquePerDay != null) T_.unique = [num(TW.uniquePerDay), 'unique viewers / stream day', 'Twitch\'s count of different people who watched, averaged over the days you streamed'];
if (TW && (TW.newEngaged || TW.returningEngaged)) T_.engaged = [num(TW.newEngaged), 'new engaged viewers', `${num(TW.returningEngaged)} returning engaged viewer-days. Engaged = watched 5+ minutes and chatted or followed (Twitch)`];
if (TW && TW.revenue) T_.revenue = [`$${TW.revenue.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`, 'revenue · admin only',
TW.revenueByType.map(([k, x]) => `${k} $${x.toFixed(2)}`).join(', ') + ' (Twitch export, before payout fees and taxes)'];
if (T.follows && !T_.followers) T_.follows = [num(T.follows), 'new followers'];
if (T.intros) T_.intros = [num(T.intros), 'first-time chatters'];
if (T.subs || T.giftSubs) T_.subs = [num(T.subs + T.giftSubs), 'subs', `${num(T.subs)} subs and resubs, ${num(T.giftSubs)} gifted`];
if (T.bits) T_.bits = [num(T.bits), 'bits', s.bitsSource === 'twitch' ? 'All time, from Twitch (top 100 cheerers)' : T.powerUps ? `${num(T.powerUps)} Power-ups included` : ''];
if (T.raids) T_.raids = [num(T.raids), T.raids === 1 ? 'raid' : 'raids', `${num(T.raidViewers)} viewers brought in`];
if (T.checkins) T_.checkins = [num(T.checkins), 'check-ins', 'First message of a stream'];
}
const order = admin
? ['followers', 'subsNow', 'messages', 'chatters', 'viewers', 'watch', 'streams', 'streamed', 'peak', 'unique', 'engaged', 'clips', 'revenue', 'follows', 'intros', 'emotes', 'subs', 'bits', 'redeems', 'raids', 'checkins']
: ['messages', 'watch', 'streams', 'streamed', 'emotes', 'clips', 'redeems'];
const tiles = order.filter(k => T_[k]).map(k => T_[k]);
%>
<% if (admin || v === 'streams') { %>
<% for (const [val, k, tip] of tiles) { %>
<%= val %>
<%= k %><%- info(tip) %>
<% } %>
<% } %>
<% if (v === 'streams') { %>
<%# ===================== STREAMS ===================== %>
<% if (r.p === 'stream' && s.streams[0]) { const x = s.streams[0]; %>
<%= day(x.started_at) %>, <%= time(x.started_at) %>–<%= x.ended_at ? time(x.ended_at) : 'now' %><%= x.games.length ? ` · ${x.games.join(', ')}` : '' %>
<% if (x.live) { %> · live now<% } %>
<% if (x.source === 'vod') { %> · from the VOD (HeyStreamer was not counting)<% } %>
<%
// viewers every 5 minutes as an area line; title / category changes as dashed markers
const tl = s.timeline;
if (tl && (tl.samples.length || tl.changes.length)) {
const W = 900, H = 200, L = 34, B = 20, TOP = 10;
const t0 = Date.parse(tl.start), t1 = Math.max(Date.parse(tl.end), t0 + 60000);
const max = Math.max(1, ...tl.samples.map(p => p.viewers));
const top = (() => { const p = Math.pow(10, Math.floor(Math.log10(max))); return [1, 2, 2.5, 5, 10].map(m => m * p).find(x => x >= max); })();
const X = t => L + (W - L) * (Date.parse(t) - t0) / (t1 - t0), Y = n => TOP + (H - TOP - B) * (1 - n / top);
let svg = `