751 lines
39 KiB
JavaScript
751 lines
39 KiB
JavaScript
const root = document.getElementById("publicTrainingRoot");
|
|
const shareToken = decodeURIComponent(window.location.pathname.split("/").filter(Boolean).at(-1) || "");
|
|
const requestedLanguage = new URLSearchParams(window.location.search).get("lang");
|
|
const language = requestedLanguage === "en" || requestedLanguage === "sv"
|
|
? requestedLanguage
|
|
: String(navigator.language || "sv").toLowerCase().startsWith("sv") ? "sv" : "en";
|
|
const DEFAULT_TIMER_CONFIG = Object.freeze({ pushMinutes: 10, controlMinutes: 10 });
|
|
const MAX_TIMER_BLOCK_MINUTES = 120;
|
|
let selectedClassId = new URLSearchParams(window.location.search).get("class") || "";
|
|
|
|
const messages = {
|
|
sv: {
|
|
loading: "Laddar träningsprofil...",
|
|
loadError: "Kunde inte läsa träningsprofilen. Länken kan vara avstängd eller ersatt.",
|
|
development: "Förarutveckling",
|
|
class: "Klass",
|
|
laps: "Totala varv",
|
|
days: "Träningsdagar",
|
|
best: "Bästa varv",
|
|
consistency: "Jämnhet senaste 30",
|
|
nextLevel: "Nästa nivå",
|
|
reachLaps: "Nå {laps} varv",
|
|
lapsRemaining: "{laps} varv kvar",
|
|
plan: "Dagens träningspass",
|
|
timerSetup: "Ställ in passet",
|
|
pushMinutes: "Maxfokus (min)",
|
|
controlMinutes: "Kontrollerad (min)",
|
|
timerSetupHint: "Minst ett block måste vara 1 minut. Tiderna sparas för den här föraren och klassen.",
|
|
timerLockedHint: "Nollställ eller slutför passet för att ändra tiderna.",
|
|
sessionStats: "Det här passet",
|
|
sessionLaps: "Varv",
|
|
baselineTitle: "Bygg en baslinje",
|
|
baselineBody: "Kör lugnt och jämnt tills du har minst 10 rena varv. Upprepa samma linje och bromspunkt.",
|
|
consistencyTitle: "Höj din lägstanivå",
|
|
consistencyBody: "Kör första blocket nära max, sedan ett kontrollerat block på 80-90 procent med fokus på rena, repeterbara varv.",
|
|
progressionTitle: "Balansera fart och kontroll",
|
|
progressionBody: "Kör ett block med maxfokus och avsluta med ett kontrollerat block utan misstag.",
|
|
target: "Kontrollmål {lap}",
|
|
ready: "Redo att börja",
|
|
push: "Maxfokus: hitta gränsen",
|
|
control: "80-90%: höj lägstanivån",
|
|
finished: "Passet är klart",
|
|
start: "Starta pass",
|
|
pause: "Pausa",
|
|
resume: "Fortsätt",
|
|
running: "Pågår",
|
|
reset: "Nollställ",
|
|
goals: "Mål och belöningar",
|
|
noGoals: "Inga personliga mål har lagts till ännu.",
|
|
goalReached: "Målet är nått",
|
|
rewardDelivered: "Belöning utdelad",
|
|
reward: "Belöning",
|
|
history: "Senaste träningsdagar",
|
|
date: "Datum",
|
|
dayLaps: "Varv",
|
|
average: "Snitt",
|
|
updated: "Uppdaterad {time}",
|
|
switchCue: "Byt till kontrollerad körning",
|
|
finishCue: "Träningspasset är klart",
|
|
performance: "Stintstatistik",
|
|
paceChart: "Tempoutveckling",
|
|
paceChartHint: "Senaste träningsdagarnas snittempo i vald klass. Lägre är snabbare.",
|
|
stintDetails: "Senaste stintar",
|
|
stintNumber: "Stint",
|
|
duration: "Tid",
|
|
noStints: "Inga stintar registrerade ännu.",
|
|
stints: "Stints",
|
|
bestThree: "Bästa 3 sammanhängande",
|
|
bestFive: "Bästa 5 min",
|
|
fiveAverage: "Avg pace, bästa 5 min",
|
|
splitPassings: "Mellantidspasseringar",
|
|
bestSplit: "Bästa mellantid",
|
|
latestSectorGain: "Senaste sektorförbättring",
|
|
controlZone: "Kontrollzon",
|
|
outlierLaps: "Avvikande varv",
|
|
strongFinishes: "Starka avslutningar",
|
|
pitStops: "Depåstopp",
|
|
totalPit: "Total depåtid",
|
|
recentProgress: "Din senaste utveckling",
|
|
averagePace: "Snittempo",
|
|
collectingTrend: "Samlar jämförbart underlag",
|
|
fasterTrend: "{lap} snabbare per varv",
|
|
slowerTrend: "{lap} långsammare just nu",
|
|
stableTrend: "Stabil nivå",
|
|
achievements: "Achievements",
|
|
unlocked: "Upplåst",
|
|
nextAchievement: "Nästa delmål",
|
|
achievement_first_session: "Första träningspasset",
|
|
achievement_laps_100: "100 träningsvarv",
|
|
achievement_laps_250: "250 träningsvarv",
|
|
achievement_laps_500: "500 träningsvarv",
|
|
achievement_laps_1000: "1 000 träningsvarv",
|
|
achievement_laps_1500: "1 500 träningsvarv",
|
|
achievement_days_3: "3 träningsdagar",
|
|
achievement_days_10: "10 träningsdagar",
|
|
achievement_sessions_5: "5 fullföljda träningspass",
|
|
achievement_controlled_5: "5 kontrollerade varv i rad",
|
|
achievement_controlled_10: "10 kontrollerade varv i rad",
|
|
achievement_five_minute: "Fullföljd femminutersstint",
|
|
achievement_five_minutes_3: "3 fullföljda femminutersstintar",
|
|
achievement_consistency_5: "Jämnhet under 5 procent",
|
|
achievement_strong_finish: "Stark avslutning",
|
|
achievement_clean_five_minute: "Fem minuter utan avvikande varv",
|
|
achievement_pace_gain: "Förbättrat snittempo",
|
|
creditTitle: "Din träning räknas",
|
|
creditBody: "Varje genomfört varv bygger erfarenhet. Du jämförs med din egen utveckling, inte med andra förare.",
|
|
todayLapsCredit: "{laps} giltiga varv idag",
|
|
paceCredit: "Snittempot är {lap} snabbare per varv",
|
|
consistencyCredit: "{value} procentenheter jämnare körning",
|
|
controlledCredit: "{laps} kontrollerade varv i rad",
|
|
fiveMinuteCredit: "Du har fullföljt en femminutersstint",
|
|
sectorCredit: "Sektortiden förbättrad med {lap}",
|
|
strongFinishCredit: "Stark avslutning med bibehållet tempo",
|
|
cleanFiveCredit: "Fem minuter utan avvikande varv",
|
|
buildingCredit: "{laps} varv har redan byggt din erfarenhet",
|
|
readyCredit: "Första giltiga varvet startar din utvecklingsresa",
|
|
challenges: "Små utmaningar",
|
|
challengesHint: "Valfria mål som ger kredit för mängd, kontroll och uthållighet.",
|
|
challengeLaps: "Samla 20 varv idag",
|
|
challengeControlled: "Kör 5 kontrollerade varv i rad",
|
|
challengeFive: "Fullfölj en femminutersstint",
|
|
challengeProgress: "{current} / {target}",
|
|
},
|
|
en: {
|
|
loading: "Loading training profile...",
|
|
loadError: "The training profile could not be loaded. The link may be disabled or replaced.",
|
|
development: "Driver development",
|
|
class: "Class",
|
|
laps: "Total laps",
|
|
days: "Practice days",
|
|
best: "Best lap",
|
|
consistency: "Latest 30 consistency",
|
|
nextLevel: "Next level",
|
|
reachLaps: "Reach {laps} laps",
|
|
lapsRemaining: "{laps} laps remaining",
|
|
plan: "Today's practice session",
|
|
timerSetup: "Set session duration",
|
|
pushMinutes: "Maximum focus (min)",
|
|
controlMinutes: "Controlled (min)",
|
|
timerSetupHint: "At least one block must be 1 minute. Times are saved for this driver and class.",
|
|
timerLockedHint: "Reset or finish the session to change the times.",
|
|
sessionStats: "This session",
|
|
sessionLaps: "Laps",
|
|
baselineTitle: "Build a baseline",
|
|
baselineBody: "Drive calmly and consistently until at least 10 clean laps are recorded. Repeat the same line and braking point.",
|
|
consistencyTitle: "Raise your minimum level",
|
|
consistencyBody: "Run the first block near maximum pace, then a controlled block at 80-90 percent with clean, repeatable laps.",
|
|
progressionTitle: "Balance pace and control",
|
|
progressionBody: "Run one block at maximum focus and finish with a controlled block without mistakes.",
|
|
target: "Control target {lap}",
|
|
ready: "Ready to start",
|
|
push: "Maximum focus: find the limit",
|
|
control: "80-90%: raise the floor",
|
|
finished: "Session completed",
|
|
start: "Start session",
|
|
pause: "Pause",
|
|
resume: "Resume",
|
|
running: "Running",
|
|
reset: "Reset",
|
|
goals: "Goals and rewards",
|
|
noGoals: "No personal goals have been added yet.",
|
|
goalReached: "Goal reached",
|
|
rewardDelivered: "Reward delivered",
|
|
reward: "Reward",
|
|
history: "Latest practice days",
|
|
date: "Date",
|
|
dayLaps: "Laps",
|
|
average: "Average",
|
|
updated: "Updated {time}",
|
|
switchCue: "Switch to controlled driving",
|
|
finishCue: "The training session is complete",
|
|
performance: "Stint statistics",
|
|
paceChart: "Pace development",
|
|
paceChartHint: "Average pace for recent practice days in the selected class. Lower is faster.",
|
|
stintDetails: "Recent stints",
|
|
stintNumber: "Stint",
|
|
duration: "Duration",
|
|
noStints: "No stints have been recorded yet.",
|
|
stints: "Stints",
|
|
bestThree: "Best 3 consecutive",
|
|
bestFive: "Best 5 min",
|
|
fiveAverage: "Average pace, best 5 min",
|
|
splitPassings: "Split passings",
|
|
bestSplit: "Best split",
|
|
latestSectorGain: "Latest sector improvement",
|
|
controlZone: "Control zone",
|
|
outlierLaps: "Outlier laps",
|
|
strongFinishes: "Strong finishes",
|
|
pitStops: "Pit stops",
|
|
totalPit: "Total pit time",
|
|
recentProgress: "Your recent development",
|
|
averagePace: "Average pace",
|
|
collectingTrend: "Collecting comparable data",
|
|
fasterTrend: "{lap} faster per lap",
|
|
slowerTrend: "{lap} slower right now",
|
|
stableTrend: "Stable level",
|
|
achievements: "Achievements",
|
|
unlocked: "Unlocked",
|
|
nextAchievement: "Next milestone",
|
|
achievement_first_session: "First practice session",
|
|
achievement_laps_100: "100 practice laps",
|
|
achievement_laps_250: "250 practice laps",
|
|
achievement_laps_500: "500 practice laps",
|
|
achievement_laps_1000: "1,000 practice laps",
|
|
achievement_laps_1500: "1,500 practice laps",
|
|
achievement_days_3: "3 practice days",
|
|
achievement_days_10: "10 practice days",
|
|
achievement_sessions_5: "5 completed practice sessions",
|
|
achievement_controlled_5: "5 controlled laps in a row",
|
|
achievement_controlled_10: "10 controlled laps in a row",
|
|
achievement_five_minute: "Completed five-minute stint",
|
|
achievement_five_minutes_3: "3 completed five-minute stints",
|
|
achievement_consistency_5: "Consistency below 5 percent",
|
|
achievement_strong_finish: "Strong finish",
|
|
achievement_clean_five_minute: "Five minutes without outlier laps",
|
|
achievement_pace_gain: "Improved average pace",
|
|
creditTitle: "Your practice counts",
|
|
creditBody: "Every completed lap builds experience. You are compared with your own development, not other drivers.",
|
|
todayLapsCredit: "{laps} valid laps today",
|
|
paceCredit: "Average pace is {lap} faster per lap",
|
|
consistencyCredit: "{value} percentage points more consistent",
|
|
controlledCredit: "{laps} controlled laps in a row",
|
|
fiveMinuteCredit: "You completed a five-minute stint",
|
|
sectorCredit: "Sector time improved by {lap}",
|
|
strongFinishCredit: "Strong finish with pace maintained",
|
|
cleanFiveCredit: "Five minutes without outlier laps",
|
|
buildingCredit: "{laps} laps have already built your experience",
|
|
readyCredit: "Your first valid lap starts the development journey",
|
|
challenges: "Small challenges",
|
|
challengesHint: "Optional goals that recognize volume, control, and endurance.",
|
|
challengeLaps: "Collect 20 laps today",
|
|
challengeControlled: "Run 5 controlled laps in a row",
|
|
challengeFive: "Complete a five-minute stint",
|
|
challengeProgress: "{current} / {target}",
|
|
},
|
|
};
|
|
|
|
let profileData = null;
|
|
let timerHandle = null;
|
|
let lastTimerPhase = "";
|
|
|
|
function t(key, vars = {}) {
|
|
const template = messages[language]?.[key] || messages.en[key] || key;
|
|
return String(template).replace(/\{(\w+)\}/g, (_, name) => String(vars[name] ?? ""));
|
|
}
|
|
|
|
function escapeHtml(value) {
|
|
return String(value ?? "")
|
|
.replaceAll("&", "&")
|
|
.replaceAll("<", "<")
|
|
.replaceAll(">", ">")
|
|
.replaceAll('"', """)
|
|
.replaceAll("'", "'");
|
|
}
|
|
|
|
function formatLap(ms) {
|
|
const value = Math.max(0, Number(ms || 0));
|
|
if (!value) return "-";
|
|
const minutes = Math.floor(value / 60000);
|
|
const seconds = Math.floor((value % 60000) / 1000);
|
|
const millis = Math.floor(value % 1000);
|
|
return `${minutes}:${String(seconds).padStart(2, "0")}.${String(millis).padStart(3, "0")}`;
|
|
}
|
|
|
|
function formatRaceResultTime(ms) {
|
|
const value = Math.max(0, Math.floor(Number(ms || 0)));
|
|
const minutes = Math.floor(value / 60000);
|
|
const seconds = Math.floor((value % 60000) / 1000);
|
|
const centiseconds = Math.floor((value % 1000) / 10);
|
|
const millis = Math.floor(value % 1000);
|
|
return `${String(minutes).padStart(2, "0")}:${String(seconds).padStart(2, "0")}.${String(centiseconds).padStart(2, "0")}:${String(millis).padStart(3, "0")}`;
|
|
}
|
|
|
|
function formatTimer(ms) {
|
|
const seconds = Math.max(0, Math.ceil(ms / 1000));
|
|
return `${String(Math.floor(seconds / 60)).padStart(2, "0")}:${String(seconds % 60).padStart(2, "0")}`;
|
|
}
|
|
|
|
function recommendationCopy(recommendation) {
|
|
const level = ["baseline", "consistency", "progression"].includes(recommendation?.level) ? recommendation.level : "baseline";
|
|
return {
|
|
title: t(`${level}Title`),
|
|
body: t(`${level}Body`),
|
|
};
|
|
}
|
|
|
|
function getLocalDayKey(timestamp) {
|
|
const date = new Date(Number(timestamp || 0));
|
|
if (Number.isNaN(date.getTime())) return "";
|
|
return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, "0")}-${String(date.getDate()).padStart(2, "0")}`;
|
|
}
|
|
|
|
function buildProfileMotivation(stats, channelStats = {}) {
|
|
const todayKey = getLocalDayKey(Date.now());
|
|
const today = (Array.isArray(stats?.dailySummaries) ? stats.dailySummaries : []).find((day) => day.dateKey === todayKey);
|
|
const activeToday = Boolean(today);
|
|
const todayLaps = Number(today?.laps || 0);
|
|
const controlled = activeToday ? Number(stats?.todayControlledLapStreak || 0) : 0;
|
|
const completedFive = activeToday ? Number(stats?.todayCompletedFiveMinuteStints || 0) : 0;
|
|
const challenges = [
|
|
{ id: "Laps", current: todayLaps, target: 20 },
|
|
{ id: "Controlled", current: controlled, target: 5 },
|
|
{ id: "Five", current: completedFive, target: 1 },
|
|
].map((challenge) => ({
|
|
...challenge,
|
|
percent: Math.min(100, Math.max(0, (challenge.current / challenge.target) * 100)),
|
|
completed: challenge.current >= challenge.target,
|
|
}));
|
|
const credits = [];
|
|
if (todayLaps) credits.push(t("todayLapsCredit", { laps: todayLaps }));
|
|
if (stats?.trendSampleReady && Number(stats.averageTrendMs || 0) > 0) credits.push(t("paceCredit", { lap: formatLap(stats.averageTrendMs) }));
|
|
if (stats?.trendSampleReady && Number(stats.consistencyTrendPct || 0) > 0.1) credits.push(t("consistencyCredit", { value: Number(stats.consistencyTrendPct).toFixed(1) }));
|
|
if (controlled >= 5) credits.push(t("controlledCredit", { laps: controlled }));
|
|
if (completedFive) credits.push(t("fiveMinuteCredit"));
|
|
if (Number(channelStats.latestSplitGainMs || 0) > 0) credits.push(t("sectorCredit", { lap: formatLap(channelStats.latestSplitGainMs) }));
|
|
if (Number(stats?.todayStrongFinishStints || 0) > 0) credits.push(t("strongFinishCredit"));
|
|
if (Number(stats?.todayCleanFiveMinuteStints || 0) > 0) credits.push(t("cleanFiveCredit"));
|
|
if (!credits.length && Number(stats?.totalLaps || 0) > 0) credits.push(t("buildingCredit", { laps: stats.totalLaps }));
|
|
if (!credits.length) credits.push(t("readyCredit"));
|
|
return { challenges, credits: credits.slice(0, 3) };
|
|
}
|
|
|
|
function renderPaceChart(points) {
|
|
const values = (Array.isArray(points) ? points : []).slice().reverse().filter((point) => Number(point.averageLapMs || 0) > 0);
|
|
if (values.length < 2) return `<p class="profile-empty">${escapeHtml(t("collectingTrend"))}</p>`;
|
|
const width = 640, height = 180, padding = 24;
|
|
const lapTimes = values.map((point) => Number(point.averageLapMs));
|
|
const min = Math.min(...lapTimes);
|
|
const range = Math.max(1, Math.max(...lapTimes) - min);
|
|
const coordinates = values.map((point, index) => ({ x: padding + (index / Math.max(1, values.length - 1)) * (width - padding * 2), y: padding + ((Number(point.averageLapMs) - min) / range) * (height - padding * 2), point }));
|
|
const path = coordinates.map((point) => `${point.x.toFixed(1)},${point.y.toFixed(1)}`).join(" ");
|
|
return `<div class="profile-pace-chart"><svg viewBox="0 0 ${width} ${height}" role="img" aria-label="${escapeHtml(t("paceChart"))}"><polyline class="profile-pace-line" points="${path}" />${coordinates.map((item) => `<circle cx="${item.x.toFixed(1)}" cy="${item.y.toFixed(1)}" r="5"><title>${escapeHtml(item.point.dateKey)}: ${escapeHtml(formatLap(item.point.averageLapMs))}</title></circle>`).join("")}</svg><div class="profile-chart-labels"><span>${escapeHtml(values[0].dateKey)}</span><strong>${escapeHtml(formatLap(values.at(-1).averageLapMs))}</strong><span>${escapeHtml(values.at(-1).dateKey)}</span></div></div>`;
|
|
}
|
|
function renderProfile(data) {
|
|
profileData = data;
|
|
const { profile, branding } = data;
|
|
const visibility = { progress: true, achievements: true, performance: true, goals: true, history: true, ...(data.visibility || {}) };
|
|
const classProfiles = Array.isArray(data.classProfiles) ? data.classProfiles : [];
|
|
let activeClass = classProfiles.find((item) => String(item.classId || "") === selectedClassId) || classProfiles[0] || null;
|
|
if (activeClass && selectedClassId !== activeClass.classId) selectedClassId = activeClass.classId;
|
|
const stats = { dailySummaries: [], paceHistory: [], achievements: [], stintSummaries: [], ...(activeClass?.stats || data.stats || {}) };
|
|
const channelStats = activeClass?.channelStats || data.channelStats || {};
|
|
const nextMilestone = activeClass?.nextMilestone || data.nextMilestone;
|
|
const recommendation = activeClass?.recommendation || data.recommendation;
|
|
const goals = activeClass?.goals || data.goals || [];
|
|
const currentSession = activeClass?.currentSession || data.currentSession;
|
|
const motivation = buildProfileMotivation(stats, channelStats);
|
|
const recommendationText = recommendationCopy(recommendation);
|
|
const timerState = readTimerState();
|
|
const timerConfig = getTimerConfig(timerState);
|
|
const timerDurationMs = getTimerDurationMs(timerConfig);
|
|
const timerLocked = Boolean(timerState?.startedAt && getTimerElapsed(timerState) < timerDurationMs);
|
|
const achievements = Array.isArray(stats.achievements) ? stats.achievements : [];
|
|
const unlockedAchievements = achievements.filter((achievement) => achievement.unlocked);
|
|
const nextAchievement = achievements.find((achievement) => !achievement.unlocked);
|
|
const visibleAchievements = [...unlockedAchievements.slice(-5), ...(nextAchievement ? [nextAchievement] : [])];
|
|
const achievementMarkup = visibleAchievements.map((achievement) => `
|
|
<article class="profile-achievement ${achievement.unlocked ? "is-unlocked" : "is-next"}">
|
|
<span>${achievement.unlocked ? "OK" : `${Math.round(Number(achievement.percent || 0))}%`}</span>
|
|
<div><strong>${escapeHtml(t(`achievement_${achievement.id}`))}</strong><small>${escapeHtml(t(achievement.unlocked ? "unlocked" : "nextAchievement"))}</small></div>
|
|
</article>
|
|
`).join("");
|
|
const creditMarkup = motivation.credits.map((credit) => `<li><span>+</span><strong>${escapeHtml(credit)}</strong></li>`).join("");
|
|
const challengeMarkup = motivation.challenges.map((challenge) => `
|
|
<article class="profile-challenge ${challenge.completed ? "is-complete" : ""}">
|
|
<span>${challenge.completed ? "OK" : `${Math.round(challenge.percent)}%`}</span>
|
|
<div>
|
|
<strong>${escapeHtml(t(`challenge${challenge.id}`))}</strong>
|
|
<small>${escapeHtml(t("challengeProgress", { current: challenge.current, target: challenge.target }))}</small>
|
|
<div class="profile-progress"><span style="width:${challenge.percent.toFixed(2)}%"></span></div>
|
|
</div>
|
|
</article>
|
|
`).join("");
|
|
const paceTrend = !stats.trendSampleReady
|
|
? t("collectingTrend")
|
|
: stats.averageTrendMs > 0
|
|
? t("fasterTrend", { lap: formatLap(stats.averageTrendMs) })
|
|
: stats.averageTrendMs < 0
|
|
? t("slowerTrend", { lap: formatLap(Math.abs(stats.averageTrendMs)) })
|
|
: t("stableTrend");
|
|
const logo = /^data:image\/(?:png|jpeg|webp);base64,/i.test(branding.logoDataUrl || "")
|
|
? `<img src="${escapeHtml(branding.logoDataUrl)}" alt="" />`
|
|
: `<div class="profile-brand-mark">RC</div>`;
|
|
const goalMarkup = goals.length
|
|
? goals.map((goal) => `
|
|
<article class="profile-goal ${goal.reached ? "reached" : ""}">
|
|
<div class="profile-goal-row">
|
|
<strong>${escapeHtml(goal.title || t("reachLaps", { laps: goal.targetLaps }))}</strong>
|
|
<span>${goal.currentLaps} / ${goal.targetLaps}</span>
|
|
</div>
|
|
<div class="profile-progress"><span style="width:${Number(goal.percent || 0).toFixed(2)}%"></span></div>
|
|
${goal.reward ? `<p><span class="profile-mini-label">${escapeHtml(t("reward"))}</span><br />${escapeHtml(goal.reward)}</p>` : ""}
|
|
${goal.claimed ? `<span class="profile-mini-label">${escapeHtml(t("rewardDelivered"))}</span>` : goal.reached ? `<span class="profile-mini-label">${escapeHtml(t("goalReached"))}</span>` : ""}
|
|
</article>
|
|
`).join("")
|
|
: `<p class="profile-empty">${escapeHtml(t("noGoals"))}</p>`;
|
|
const historyRows = stats.dailySummaries.length
|
|
? stats.dailySummaries.slice(0, 12).map((day) => `
|
|
<tr>
|
|
<td>${escapeHtml(new Date(day.latestTimestamp).toLocaleDateString(language))}</td>
|
|
<td>${day.laps}</td>
|
|
<td>${formatLap(day.bestLapMs)}</td>
|
|
<td>${formatLap(day.averageLapMs)}</td>
|
|
</tr>
|
|
`).join("")
|
|
: `<tr><td colspan="4">-</td></tr>`;
|
|
const stintRows = stats.stintSummaries.length ? stats.stintSummaries.slice(0, 6).map((stint) => `
|
|
<tr><td>${stint.number}</td><td>${escapeHtml(new Date(stint.startedAt).toLocaleString(language, { dateStyle: "short", timeStyle: "short" }))}</td><td>${stint.lapCount}</td><td>${formatLap(stint.bestLapMs)}</td><td>${formatLap(stint.averageLapMs)}</td><td>${formatRaceResultTime(stint.durationMs)}</td></tr>
|
|
`).join("") : `<tr><td colspan="6">${escapeHtml(t("noStints"))}</td></tr>`;
|
|
const classOptions = classProfiles.map((item) => (
|
|
`<option value="${escapeHtml(item.classId)}" ${item.classId === selectedClassId ? "selected" : ""}>${escapeHtml(item.className || item.classId)}</option>`
|
|
)).join("");
|
|
|
|
document.documentElement.lang = language;
|
|
document.title = `${profile.name} - ${branding.clubName}`;
|
|
root.innerHTML = `
|
|
<header class="profile-header">
|
|
<div class="profile-brand">
|
|
${logo}
|
|
<div><strong>${escapeHtml(branding.clubName)}</strong><span>${escapeHtml(branding.clubTagline)}</span></div>
|
|
</div>
|
|
<div class="profile-updated">${escapeHtml(t("updated", { time: new Date(data.updatedAt || Date.now()).toLocaleString(language) }))}</div>
|
|
</header>
|
|
|
|
<section class="profile-hero">
|
|
<span class="profile-eyebrow">${escapeHtml(t("development"))}</span>
|
|
<h1>${escapeHtml(profile.name)}</h1>
|
|
<div class="profile-meta">
|
|
${classProfiles.length > 1 ? `<label class="profile-class-select"><span>${escapeHtml(t("class"))}</span><select id="profileClass">${classOptions}</select></label>` : activeClass?.className ? `<span class="profile-pill">${escapeHtml(activeClass.className)}</span>` : ""}
|
|
${activeClass?.brand ? `<span class="profile-pill">${escapeHtml(activeClass.brand)}</span>` : ""}
|
|
</div>
|
|
</section>
|
|
|
|
<section class="profile-stat-grid">
|
|
${renderStat(t("laps"), stats.totalLaps)}
|
|
${renderStat(t("days"), stats.trainingDays)}
|
|
${renderStat(t("best"), formatLap(stats.bestLapMs))}
|
|
${renderStat(t("consistency"), stats.recentLapCount ? `${Number(stats.consistencySpreadPct).toFixed(1)}%` : "-")}
|
|
</section>
|
|
|
|
<section class="profile-motivation-grid">
|
|
<article class="profile-card profile-credit-card">
|
|
<span class="profile-mini-label">${escapeHtml(t("creditTitle"))}</span>
|
|
<p>${escapeHtml(t("creditBody"))}</p>
|
|
<ul>${creditMarkup}</ul>
|
|
</article>
|
|
<article class="profile-card profile-challenge-card">
|
|
<div class="profile-growth-head"><span class="profile-mini-label">${escapeHtml(t("challenges"))}</span><strong>${motivation.challenges.filter((challenge) => challenge.completed).length}/${motivation.challenges.length}</strong></div>
|
|
<p>${escapeHtml(t("challengesHint"))}</p>
|
|
<div class="profile-challenges">${challengeMarkup}</div>
|
|
</article>
|
|
</section>
|
|
|
|
<section class="profile-growth-grid ${visibility.progress || visibility.achievements ? "" : "is-hidden"}">
|
|
<article class="profile-card profile-growth-card ${visibility.progress ? "" : "is-hidden"}">
|
|
<span class="profile-mini-label">${escapeHtml(t("recentProgress"))}</span>
|
|
<strong>${escapeHtml(t("averagePace"))}</strong>
|
|
<p>${escapeHtml(paceTrend)}</p>
|
|
</article>
|
|
<article class="profile-card profile-growth-card ${visibility.achievements ? "" : "is-hidden"}">
|
|
<div class="profile-growth-head"><span class="profile-mini-label">${escapeHtml(t("achievements"))}</span><strong>${unlockedAchievements.length}/${achievements.length}</strong></div>
|
|
<div class="profile-achievements">${achievementMarkup}</div>
|
|
</article>
|
|
</section>
|
|
|
|
<section class="profile-card profile-chart-card ${visibility.progress ? "" : "is-hidden"}">
|
|
<div class="profile-card-head"><div><h2>${escapeHtml(t("paceChart"))}</h2><p>${escapeHtml(t("paceChartHint"))}</p></div></div>
|
|
${renderPaceChart(stats.paceHistory)}
|
|
</section>
|
|
<div class="profile-grid">
|
|
<section class="profile-card">
|
|
<div class="profile-card-head"><h2>${escapeHtml(t("nextLevel"))}</h2></div>
|
|
<div class="profile-card-body">
|
|
<div class="profile-level-row">
|
|
<div><span class="profile-mini-label">${escapeHtml(t("lapsRemaining", { laps: nextMilestone.remainingLaps }))}</span><h3>${escapeHtml(t("reachLaps", { laps: nextMilestone.targetLaps }))}</h3></div>
|
|
<strong>${nextMilestone.currentLaps} / ${nextMilestone.targetLaps}</strong>
|
|
</div>
|
|
<div class="profile-progress"><span style="width:${Number(nextMilestone.percent || 0).toFixed(2)}%"></span></div>
|
|
</div>
|
|
</section>
|
|
|
|
<section class="profile-card">
|
|
<div class="profile-card-head"><h2>${escapeHtml(t("plan"))}</h2></div>
|
|
<div class="profile-card-body">
|
|
<span class="profile-mini-label">${recommendation.targetLapMs ? escapeHtml(t("target", { lap: formatLap(recommendation.targetLapMs) })) : ""}</span>
|
|
<h3>${escapeHtml(recommendationText.title)}</h3>
|
|
<p class="profile-plan-copy">${escapeHtml(recommendationText.body)}</p>
|
|
<fieldset id="profileTimerSetup" class="profile-timer-setup" ${timerLocked ? "disabled" : ""}>
|
|
<legend>${escapeHtml(t("timerSetup"))}</legend>
|
|
<label><span>${escapeHtml(t("pushMinutes"))}</span><input id="profilePushMinutes" type="number" min="0" max="${MAX_TIMER_BLOCK_MINUTES}" step="1" value="${timerConfig.pushMinutes}" /></label>
|
|
<label><span>${escapeHtml(t("controlMinutes"))}</span><input id="profileControlMinutes" type="number" min="0" max="${MAX_TIMER_BLOCK_MINUTES}" step="1" value="${timerConfig.controlMinutes}" /></label>
|
|
<small id="profileTimerSetupHint">${escapeHtml(t(timerLocked ? "timerLockedHint" : "timerSetupHint"))}</small>
|
|
</fieldset>
|
|
<div id="profileTimer" class="profile-timer">${formatTimer(timerDurationMs)}</div>
|
|
<div id="profileTimerPhase" class="profile-timer-phase">${escapeHtml(t("ready"))}</div>
|
|
${currentSession ? `
|
|
<div class="profile-session-heading">${escapeHtml(t("sessionStats"))}</div>
|
|
<div class="profile-session-stats">
|
|
<div><span>${escapeHtml(t("sessionLaps"))}</span><strong>${currentSession.laps}</strong></div>
|
|
<div><span>${escapeHtml(t("best"))}</span><strong>${formatLap(currentSession.bestLapMs)}</strong></div>
|
|
<div><span>${escapeHtml(t("average"))}</span><strong>${formatLap(currentSession.averageLapMs)}</strong></div>
|
|
</div>
|
|
` : ""}
|
|
<div class="profile-actions">
|
|
<button id="profileTimerStart" class="profile-button profile-button-primary" type="button">${escapeHtml(t("start"))}</button>
|
|
<button id="profileTimerPause" class="profile-button" type="button">${escapeHtml(t("pause"))}</button>
|
|
<button id="profileTimerReset" class="profile-button" type="button">${escapeHtml(t("reset"))}</button>
|
|
</div>
|
|
</div>
|
|
</section>
|
|
</div>
|
|
|
|
<details class="profile-card profile-disclosure profile-performance ${visibility.performance ? "" : "is-hidden"}" style="margin-top:14px">
|
|
<summary class="profile-card-head"><h2>${escapeHtml(t("performance"))}</h2><span>+</span></summary>
|
|
<div class="profile-performance-stats">
|
|
<div><span>${escapeHtml(t("stints"))}</span><strong>${Number(stats.stintCount || 0)}</strong></div>
|
|
<div><span>${escapeHtml(t("controlZone"))}</span><strong>${stats.controlZoneMaxMs ? `${formatLap(stats.controlZoneMinMs)} - ${formatLap(stats.controlZoneMaxMs)}` : "-"}</strong></div>
|
|
<div><span>${escapeHtml(t("outlierLaps"))}</span><strong>${Number(stats.outlierLaps || 0)}</strong></div>
|
|
<div><span>${escapeHtml(t("strongFinishes"))}</span><strong>${Number(stats.strongFinishStints || 0)}</strong></div>
|
|
<div><span>${escapeHtml(t("bestThree"))}</span><strong>${stats.bestThreeConsecutive ? `3/${formatRaceResultTime(stats.bestThreeConsecutive.totalMs)}` : "-"}</strong></div>
|
|
<div><span>${escapeHtml(t("bestFive"))}</span><strong>${stats.bestFiveMinuteResult ? `${stats.bestFiveMinuteResult.lapCount}/${formatRaceResultTime(stats.bestFiveMinuteResult.totalMs)}` : "-"}</strong></div>
|
|
<div><span>${escapeHtml(t("fiveAverage"))}</span><strong>${stats.bestFiveMinuteResult ? formatLap(stats.bestFiveMinuteResult.averageLapMs) : "-"}</strong></div>
|
|
<div><span>${escapeHtml(t("splitPassings"))}</span><strong>${Number(channelStats.splitCount || 0)}</strong></div>
|
|
<div><span>${escapeHtml(t("bestSplit"))}</span><strong>${channelStats.splitCount ? formatLap(channelStats.bestSplitMs) : "-"}</strong></div>
|
|
<div><span>${escapeHtml(t("latestSectorGain"))}</span><strong>${channelStats.latestSplitGainMs ? formatLap(channelStats.latestSplitGainMs) : "-"}</strong></div>
|
|
<div><span>${escapeHtml(t("pitStops"))}</span><strong>${Number(channelStats.pitStopCount || 0)}</strong></div>
|
|
<div><span>${escapeHtml(t("totalPit"))}</span><strong>${channelStats.pitStopCount ? formatRaceResultTime(channelStats.totalPitMs) : "-"}</strong></div>
|
|
</div>
|
|
<div class="profile-stint-table-wrap">
|
|
<h3>${escapeHtml(t("stintDetails"))}</h3>
|
|
<div class="profile-history-wrap"><table class="profile-history"><thead><tr><th>${escapeHtml(t("stintNumber"))}</th><th>${escapeHtml(t("date"))}</th><th>${escapeHtml(t("laps"))}</th><th>${escapeHtml(t("best"))}</th><th>${escapeHtml(t("average"))}</th><th>${escapeHtml(t("duration"))}</th></tr></thead><tbody>${stintRows}</tbody></table></div>
|
|
</div>
|
|
</details>
|
|
|
|
${visibility.goals && goals.length ? `
|
|
<section class="profile-card" style="margin-top:14px">
|
|
<div class="profile-card-head"><h2>${escapeHtml(t("goals"))}</h2></div>
|
|
<div class="profile-card-body profile-goals">${goalMarkup}</div>
|
|
</section>
|
|
` : ""}
|
|
|
|
<details class="profile-card profile-disclosure ${visibility.history ? "" : "is-hidden"}" style="margin-top:14px">
|
|
<summary class="profile-card-head"><h2>${escapeHtml(t("history"))}</h2><span>+</span></summary>
|
|
<div class="profile-history-wrap">
|
|
<table class="profile-history">
|
|
<thead><tr><th>${escapeHtml(t("date"))}</th><th>${escapeHtml(t("dayLaps"))}</th><th>${escapeHtml(t("best"))}</th><th>${escapeHtml(t("average"))}</th></tr></thead>
|
|
<tbody>${historyRows}</tbody>
|
|
</table>
|
|
</div>
|
|
</details>
|
|
`;
|
|
document.getElementById("profileClass")?.addEventListener("change", (event) => {
|
|
selectedClassId = String(event.currentTarget.value || "");
|
|
const nextUrl = new URL(window.location.href);
|
|
if (selectedClassId) nextUrl.searchParams.set("class", selectedClassId);
|
|
else nextUrl.searchParams.delete("class");
|
|
window.history.replaceState({}, "", nextUrl);
|
|
lastTimerPhase = "";
|
|
renderProfile(profileData);
|
|
});
|
|
bindTimerControls();
|
|
updateTimerDisplay();
|
|
}
|
|
|
|
function renderStat(label, value) {
|
|
return `<article class="profile-card profile-stat"><span>${escapeHtml(label)}</span><strong>${escapeHtml(value)}</strong></article>`;
|
|
}
|
|
|
|
function readTimerState() {
|
|
try {
|
|
const parsed = JSON.parse(localStorage.getItem(getTimerStorageKey()) || "null");
|
|
return parsed && typeof parsed === "object" ? parsed : null;
|
|
} catch {
|
|
return null;
|
|
}
|
|
}
|
|
|
|
function normalizeTimerConfig(value) {
|
|
const clampMinutes = (minutes) => Math.max(0, Math.min(MAX_TIMER_BLOCK_MINUTES, Math.round(Number(minutes) || 0)));
|
|
const config = {
|
|
pushMinutes: clampMinutes(value?.pushMinutes),
|
|
controlMinutes: clampMinutes(value?.controlMinutes),
|
|
};
|
|
return config.pushMinutes + config.controlMinutes > 0 ? config : { ...DEFAULT_TIMER_CONFIG };
|
|
}
|
|
|
|
function readTimerConfig() {
|
|
try {
|
|
return normalizeTimerConfig(JSON.parse(localStorage.getItem(getTimerConfigStorageKey()) || "null") || DEFAULT_TIMER_CONFIG);
|
|
} catch {
|
|
return { ...DEFAULT_TIMER_CONFIG };
|
|
}
|
|
}
|
|
|
|
function writeTimerConfig(value) {
|
|
const config = normalizeTimerConfig(value);
|
|
localStorage.setItem(getTimerConfigStorageKey(), JSON.stringify(config));
|
|
return config;
|
|
}
|
|
|
|
function getTimerConfig(state = null) {
|
|
if (state && (state.pushMinutes != null || state.controlMinutes != null)) return normalizeTimerConfig(state);
|
|
return readTimerConfig();
|
|
}
|
|
|
|
function getTimerDurationMs(config) {
|
|
return (Number(config.pushMinutes || 0) + Number(config.controlMinutes || 0)) * 60 * 1000;
|
|
}
|
|
|
|
function writeTimerState(value) {
|
|
if (value) localStorage.setItem(getTimerStorageKey(), JSON.stringify(value));
|
|
else localStorage.removeItem(getTimerStorageKey());
|
|
}
|
|
|
|
function getTimerStorageKey() {
|
|
return `rc-training-timer:${shareToken}:${selectedClassId || "default"}`;
|
|
}
|
|
|
|
function getTimerConfigStorageKey() {
|
|
return `rc-training-timer-config:${shareToken}:${selectedClassId || "default"}`;
|
|
}
|
|
|
|
function getTimerElapsed(state, now = Date.now()) {
|
|
if (!state?.startedAt) return 0;
|
|
const endpoint = state.pausedAt || now;
|
|
return Math.max(0, endpoint - state.startedAt - Number(state.pausedTotalMs || 0));
|
|
}
|
|
|
|
function bindTimerControls() {
|
|
const saveTimerSetup = () => {
|
|
const current = readTimerState();
|
|
if (current?.startedAt && getTimerElapsed(current) < getTimerDurationMs(getTimerConfig(current))) return;
|
|
if (current?.startedAt) writeTimerState(null);
|
|
const config = writeTimerConfig({
|
|
pushMinutes: document.getElementById("profilePushMinutes")?.value,
|
|
controlMinutes: document.getElementById("profileControlMinutes")?.value,
|
|
});
|
|
const pushInput = document.getElementById("profilePushMinutes");
|
|
const controlInput = document.getElementById("profileControlMinutes");
|
|
if (pushInput) pushInput.value = String(config.pushMinutes);
|
|
if (controlInput) controlInput.value = String(config.controlMinutes);
|
|
updateTimerDisplay();
|
|
};
|
|
document.getElementById("profilePushMinutes")?.addEventListener("change", saveTimerSetup);
|
|
document.getElementById("profileControlMinutes")?.addEventListener("change", saveTimerSetup);
|
|
document.getElementById("profileTimerStart")?.addEventListener("click", () => {
|
|
const current = readTimerState();
|
|
const currentDurationMs = getTimerDurationMs(getTimerConfig(current));
|
|
if (current?.pausedAt) {
|
|
current.pausedTotalMs = Number(current.pausedTotalMs || 0) + Date.now() - current.pausedAt;
|
|
current.pausedAt = 0;
|
|
writeTimerState(current);
|
|
} else if (!current || getTimerElapsed(current) >= currentDurationMs) {
|
|
const config = readTimerConfig();
|
|
writeTimerState({ startedAt: Date.now(), pausedAt: 0, pausedTotalMs: 0, ...config });
|
|
lastTimerPhase = config.pushMinutes > 0 ? "push" : "control";
|
|
void loadProfile();
|
|
}
|
|
startTimerLoop();
|
|
updateTimerDisplay();
|
|
});
|
|
document.getElementById("profileTimerPause")?.addEventListener("click", () => {
|
|
const current = readTimerState();
|
|
if (current?.startedAt && !current.pausedAt && getTimerElapsed(current) < getTimerDurationMs(getTimerConfig(current))) {
|
|
current.pausedAt = Date.now();
|
|
writeTimerState(current);
|
|
}
|
|
updateTimerDisplay();
|
|
});
|
|
document.getElementById("profileTimerReset")?.addEventListener("click", () => {
|
|
writeTimerState(null);
|
|
lastTimerPhase = "";
|
|
updateTimerDisplay();
|
|
void loadProfile();
|
|
});
|
|
startTimerLoop();
|
|
}
|
|
|
|
function startTimerLoop() {
|
|
if (timerHandle) clearInterval(timerHandle);
|
|
timerHandle = setInterval(updateTimerDisplay, 250);
|
|
}
|
|
|
|
function updateTimerDisplay() {
|
|
const timer = document.getElementById("profileTimer");
|
|
const phase = document.getElementById("profileTimerPhase");
|
|
const startButton = document.getElementById("profileTimerStart");
|
|
const pauseButton = document.getElementById("profileTimerPause");
|
|
const timerSetup = document.getElementById("profileTimerSetup");
|
|
const timerSetupHint = document.getElementById("profileTimerSetupHint");
|
|
if (!timer || !phase || !startButton || !pauseButton) return;
|
|
const state = readTimerState();
|
|
const config = getTimerConfig(state);
|
|
const timerDurationMs = getTimerDurationMs(config);
|
|
const pushDurationMs = Number(config.pushMinutes || 0) * 60 * 1000;
|
|
const elapsed = getTimerElapsed(state);
|
|
const remaining = Math.max(0, timerDurationMs - elapsed);
|
|
const phaseName = !state?.startedAt
|
|
? "ready"
|
|
: remaining <= 0
|
|
? "finished"
|
|
: config.pushMinutes > 0 && elapsed < pushDurationMs
|
|
? "push"
|
|
: "control";
|
|
timer.textContent = formatTimer(remaining || (phaseName === "ready" ? timerDurationMs : 0));
|
|
phase.textContent = t(phaseName);
|
|
startButton.textContent = state?.pausedAt ? t("resume") : !state?.startedAt || remaining <= 0 ? t("start") : t("running");
|
|
startButton.disabled = Boolean(state?.startedAt && !state.pausedAt && remaining > 0);
|
|
pauseButton.disabled = !state?.startedAt || Boolean(state.pausedAt) || remaining <= 0;
|
|
if (timerSetup) timerSetup.disabled = Boolean(state?.startedAt && remaining > 0);
|
|
if (timerSetupHint) timerSetupHint.textContent = t(state?.startedAt && remaining > 0 ? "timerLockedHint" : "timerSetupHint");
|
|
if (state?.startedAt && !state.pausedAt && phaseName !== lastTimerPhase) {
|
|
if (lastTimerPhase === "push" && phaseName === "control" && config.controlMinutes > 0) speak(t("switchCue"));
|
|
if (phaseName === "finished") speak(t("finishCue"));
|
|
lastTimerPhase = phaseName;
|
|
}
|
|
}
|
|
|
|
function speak(text) {
|
|
if (!("speechSynthesis" in window)) return;
|
|
window.speechSynthesis.cancel();
|
|
const utterance = new SpeechSynthesisUtterance(text);
|
|
utterance.lang = language === "sv" ? "sv-SE" : "en-GB";
|
|
window.speechSynthesis.speak(utterance);
|
|
}
|
|
|
|
async function loadProfile() {
|
|
try {
|
|
const timerState = readTimerState();
|
|
const apiUrl = new URL(`/public-training/api/${encodeURIComponent(shareToken)}`, window.location.origin);
|
|
if (timerState?.startedAt) {
|
|
const now = Date.now();
|
|
const startedAgoMs = Math.max(0, now - timerState.startedAt);
|
|
const currentPauseMs = timerState.pausedAt ? Math.max(0, now - timerState.pausedAt) : 0;
|
|
const maximumWindowMs = getTimerDurationMs(getTimerConfig(timerState)) + Number(timerState.pausedTotalMs || 0) + currentPauseMs;
|
|
apiUrl.searchParams.set("startedAgoMs", String(startedAgoMs));
|
|
apiUrl.searchParams.set("windowMs", String(Math.min(startedAgoMs, maximumWindowMs)));
|
|
}
|
|
const response = await fetch(apiUrl, { cache: "no-store" });
|
|
if (!response.ok) throw new Error(`HTTP ${response.status}`);
|
|
renderProfile(await response.json());
|
|
} catch {
|
|
root.innerHTML = `<section class="public-training-error"><div class="profile-brand-mark">RC</div><h1>${escapeHtml(t("loadError"))}</h1></section>`;
|
|
}
|
|
}
|
|
|
|
loadProfile();
|
|
setInterval(() => {
|
|
if (!document.hidden) loadProfile();
|
|
}, 10000);
|