Training stats count Open/Free practice by default; laps from qualifying, heats and finals are kept and shown under Based on: Races or All, marked with race, session and series. Races are listed per race session and never split into stints. Same picker in the mobile profile. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1385 lines
79 KiB
JavaScript
1385 lines
79 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") || "";
|
||
let selectedLayout = new URLSearchParams(window.location.search).get("layout") || "current";
|
||
let selectedSource = new URLSearchParams(window.location.search).get("source") || "practice";
|
||
|
||
const messages = {
|
||
sv: {
|
||
connection_loading: "Hämtar statistik...",
|
||
connection_current: "Statistiken är uppdaterad.",
|
||
connection_failed: "Uppdateringen misslyckades. Visar senast hämtade data om de finns.",
|
||
connection_stale: "Statistiken kan vara inaktuell. Uppdatering väntar; avsluta eventuell inmatning.",
|
||
connection_last: "Senast hämtad {time}.",
|
||
connection_retry: "Försök igen",
|
||
connection_retrying: "Hämtar...",
|
||
loading: "Laddar träningsprofil...",
|
||
loadError: "Kunde inte läsa träningsprofilen. Länken kan vara avstängd eller ersatt.",
|
||
development: "Förarutveckling",
|
||
class: "Klass",
|
||
layoutStats: "Banlayout",
|
||
lapSource: "Underlag",
|
||
lapSourcePractice: "Träning",
|
||
lapSourceRace: "Race 🏁",
|
||
lapSourceAll: "Alla",
|
||
layoutCurrent: "Aktiv layout",
|
||
layoutNone: "Utan layout (före första layouten)",
|
||
layoutAll: "Alla layouter",
|
||
laps: "Totala varv",
|
||
days: "Träningsdagar",
|
||
best: "Bästa varv",
|
||
consistency: "Jämnhet senaste 30",
|
||
nextLevel: "Nästa nivå",
|
||
reachLaps: "Nå {laps} varv",
|
||
reachSessions: "Genomför {count} pass",
|
||
lapsRemaining: "{laps} varv kvar",
|
||
timerSessionTitle: "Träningspass",
|
||
exerciseHistoryTitle: "Träningshistorik",
|
||
exerciseHistoryHint: "Genomförda träningspass - jämna varv, stegträning och vanliga pass - för att se utvecklingen över tid.",
|
||
exerciseHistoryEmpty: "Inga genomförda träningspass ännu.",
|
||
exerciseHistoryEvenLaps: "Serie på {streak} varv i mål {lap}",
|
||
exerciseHistoryStepTraining: "{steps} steg, {laps} varv",
|
||
exerciseHistoryTimer: "{laps} varv, snitt {lap}",
|
||
exerciseSessionsCredit: "Du har genomfört {count} träningspass idag - snyggt jobbat!",
|
||
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",
|
||
practiceSummaryTitle: "Pass avslutat",
|
||
practiceSummaryNoLaps: "Inga varv registrerades under passet - kolla att transpondern fungerade och kör igen.",
|
||
practiceSummaryPaceFaster: "Du körde i snitt {lap} snabbare än innan.",
|
||
practiceSummaryPaceSlower: "Du körde i snitt {lap} långsammare än innan - ingen fara, alla pass är olika.",
|
||
practiceSummaryPaceStable: "Ditt tempo var i linje med tidigare pass.",
|
||
practiceSummaryPaceInsufficient: "Kör några fler pass så kan vi visa hur ditt tempo utvecklas.",
|
||
practiceSummaryConsistencyGood: "Mycket jämna varv den här gången ({pct}%).",
|
||
practiceSummaryConsistencyOk: "Ganska jämna varv ({pct}%).",
|
||
practiceSummaryConsistencyRough: "Varven varierade en del ({pct}%) - sikta på jämnare tempo nästa gång.",
|
||
practiceSummaryConsistencyInsufficient: "För få varv den här passet för att bedöma jämnheten.",
|
||
practiceSummaryGoalReached: "Du nådde \"{title}\" ({laps} varv)!",
|
||
practiceSummaryMilestoneReached: "Du passerade {laps} varv totalt!",
|
||
practiceSummaryRewardHint: "Belöning: {reward} - visa den här sidan för din coach eller förälder.",
|
||
practiceSummaryNextGoalTitle: "Nästa mål",
|
||
practiceSummaryClose: "Stäng",
|
||
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.",
|
||
paceBlocks: "Tempo per aktivt 30-minutersblock",
|
||
paceBlocksHint: "Visar bara block där bilen har registrerat giltiga varv.",
|
||
markerTitle: "Markera en biländring",
|
||
markerHint: "Sparas för vald förare och klass vid aktuell tid.",
|
||
markerType: "Typ", markerNote: "Beskrivning", markerSave: "Markera ändring nu",
|
||
markerSetup: "Ny setup", markerTires: "Däck", markerSuspension: "Dämpare", markerCar: "Bil", markerNoteType: "Anteckning",
|
||
markerSaved: "Biländringen är sparad.", markerError: "Kunde inte spara biländringen.",
|
||
blockLaps: "{laps} varv", blockMarkers: "{count} ändring(ar)",
|
||
evenLapsTitle: "Jämna varv", evenLapsEyebrow: "Övning",
|
||
evenLapsHint: "Ställ in måltid och tolerans, spara, och starta när du är redo att köra.",
|
||
evenLapsTargetLabel: "Måltid (sek)", evenLapsToleranceLabel: "Tolerans ± (sek)", evenLapsLapCountLabel: "Antal varv i serien",
|
||
evenLapsSuggestionHint: "Förslag baserat på ditt bästa varv: {lap}",
|
||
evenLapsStreak: "{current}/{target} jämna varv", evenLapsNewStreak: "Ny serie – försök slå din bästa",
|
||
evenLapsStartHint: "Kör ditt första varv för att starta en serie.",
|
||
evenLapsBestTodayLabel: "Bästa serie idag", evenLapsNotStarted: "Inte startad ännu.",
|
||
stepTrainingTitle: "Stegträning", stepTrainingEyebrow: "Övning",
|
||
stepTrainingHint: "Bygg din stegserie, spara, och starta när du är redo. Standard är pyramiden: lugnt, kontrollerat, snabbt, kontrollerat, lugnt.",
|
||
stepTrainingComplete: "Serien klar – bra jobbat!",
|
||
stepTrainingCurrent: "Steg {step}/{total}: {effort}", stepTrainingRemaining: "{laps} varv kvar",
|
||
stepTrainingCompare: "Kontrollerat steg 1: {first} · Kontrollerat steg 2: {last} ({diff})",
|
||
stepTrainingNotStarted: "Inte startad ännu.",
|
||
effortCalm: "Lugnt", effortControlled: "Kontrollerat", effortFast: "Snabbt",
|
||
saveSetup: "Spara", stop: "Stoppa",
|
||
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: {
|
||
connection_loading: "Loading statistics...",
|
||
connection_current: "Statistics are up to date.",
|
||
connection_failed: "Update failed. Showing previously loaded data if available.",
|
||
connection_stale: "Statistics may be outdated. Update pending; finish any active input.",
|
||
connection_last: "Last loaded {time}.",
|
||
connection_retry: "Retry",
|
||
connection_retrying: "Loading...",
|
||
loading: "Loading training profile...",
|
||
loadError: "The training profile could not be loaded. The link may be disabled or replaced.",
|
||
development: "Driver development",
|
||
class: "Class",
|
||
layoutStats: "Track layout",
|
||
lapSource: "Based on",
|
||
lapSourcePractice: "Practice",
|
||
lapSourceRace: "Races 🏁",
|
||
lapSourceAll: "All",
|
||
layoutCurrent: "Current layout",
|
||
layoutNone: "No layout (before the first layout)",
|
||
layoutAll: "All layouts",
|
||
laps: "Total laps",
|
||
days: "Practice days",
|
||
best: "Best lap",
|
||
consistency: "Latest 30 consistency",
|
||
nextLevel: "Next level",
|
||
reachLaps: "Reach {laps} laps",
|
||
reachSessions: "Complete {count} sessions",
|
||
lapsRemaining: "{laps} laps remaining",
|
||
timerSessionTitle: "Practice session",
|
||
exerciseHistoryTitle: "Training history",
|
||
exerciseHistoryHint: "Completed training sessions - even laps, step training and regular sessions - to see progress over time.",
|
||
exerciseHistoryEmpty: "No completed training sessions yet.",
|
||
exerciseHistoryEvenLaps: "{streak}-lap streak at target {lap}",
|
||
exerciseHistoryStepTraining: "{steps} steps, {laps} laps",
|
||
exerciseHistoryTimer: "{laps} laps, average {lap}",
|
||
exerciseSessionsCredit: "You completed {count} training session(s) today - nice work!",
|
||
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",
|
||
practiceSummaryTitle: "Practice complete",
|
||
practiceSummaryNoLaps: "No laps were recorded during this pass - check the transponder and try again.",
|
||
practiceSummaryPaceFaster: "You averaged {lap} faster than before.",
|
||
practiceSummaryPaceSlower: "You averaged {lap} slower than before - that's fine, every pass is different.",
|
||
practiceSummaryPaceStable: "Your pace matched your recent sessions.",
|
||
practiceSummaryPaceInsufficient: "Run a few more sessions and we can show how your pace is developing.",
|
||
practiceSummaryConsistencyGood: "Very even laps this time ({pct}%).",
|
||
practiceSummaryConsistencyOk: "Fairly even laps ({pct}%).",
|
||
practiceSummaryConsistencyRough: "Your laps varied a bit ({pct}%) - aim for a steadier pace next time.",
|
||
practiceSummaryConsistencyInsufficient: "Not enough laps this pass to judge consistency.",
|
||
practiceSummaryGoalReached: "You reached \"{title}\" ({laps} laps)!",
|
||
practiceSummaryMilestoneReached: "You passed {laps} total laps!",
|
||
practiceSummaryRewardHint: "Reward: {reward} - show this page to your coach or parent.",
|
||
practiceSummaryNextGoalTitle: "Next goal",
|
||
practiceSummaryClose: "Close",
|
||
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.",
|
||
paceBlocks: "Pace per active 30-minute block",
|
||
paceBlocksHint: "Only blocks containing valid recorded laps are shown.",
|
||
markerTitle: "Mark a car change",
|
||
markerHint: "Saved for the selected driver and class at the current time.",
|
||
markerType: "Type", markerNote: "Description", markerSave: "Mark change now",
|
||
markerSetup: "New setup", markerTires: "Tires", markerSuspension: "Suspension", markerCar: "Car", markerNoteType: "Note",
|
||
markerSaved: "The car change was saved.", markerError: "The car change could not be saved.",
|
||
blockLaps: "{laps} laps", blockMarkers: "{count} change(s)",
|
||
evenLapsTitle: "Even laps", evenLapsEyebrow: "Exercise",
|
||
evenLapsHint: "Set a target and tolerance, save, and start when you're ready to run.",
|
||
evenLapsTargetLabel: "Target (sec)", evenLapsToleranceLabel: "Tolerance ± (sec)", evenLapsLapCountLabel: "Laps in the streak",
|
||
evenLapsSuggestionHint: "Suggested from your best lap: {lap}",
|
||
evenLapsStreak: "{current}/{target} even laps", evenLapsNewStreak: "New streak - try to beat your best",
|
||
evenLapsStartHint: "Run your first lap to start a streak.",
|
||
evenLapsBestTodayLabel: "Best streak today", evenLapsNotStarted: "Not started yet.",
|
||
stepTrainingTitle: "Step training", stepTrainingEyebrow: "Exercise",
|
||
stepTrainingHint: "Build your step sequence, save, and start when ready. The default is the pyramid: calm, controlled, fast, controlled, calm.",
|
||
stepTrainingComplete: "Sequence complete - nice work!",
|
||
stepTrainingCurrent: "Step {step}/{total}: {effort}", stepTrainingRemaining: "{laps} laps remaining",
|
||
stepTrainingCompare: "Controlled step 1: {first} · Controlled step 2: {last} ({diff})",
|
||
stepTrainingNotStarted: "Not started yet.",
|
||
effortCalm: "Calm", effortControlled: "Controlled", effortFast: "Fast",
|
||
saveSetup: "Save", stop: "Stop",
|
||
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 exerciseKindMeta(kind) {
|
||
if (kind === "evenLaps") return { emoji: "🎯", titleKey: "evenLapsTitle" };
|
||
if (kind === "stepTraining") return { emoji: "🪜", titleKey: "stepTrainingTitle" };
|
||
return { emoji: "⏱️", titleKey: "timerSessionTitle" };
|
||
}
|
||
|
||
function nextMilestoneForLaps(laps) {
|
||
const presets = [100, 250, 500, 1000, 1500, 2500, 5000];
|
||
return presets.find((target) => target > laps) || (Math.floor(laps / 1000) + 1) * 1000;
|
||
}
|
||
|
||
// Turns the already-fetched, already-sanitized profile data into a one-time "practice just
|
||
// ended" recap: pace and consistency for this pass specifically, anything crossed *during*
|
||
// this pass (not all-time), one suggested next goal, and the reward text made prominent -
|
||
// never a comparison against other drivers.
|
||
function buildPracticeSummary({ currentSession, stats, goals, recommendation, nextMilestone }) {
|
||
const laps = currentSession?.laps || 0;
|
||
if (!laps) return { laps: 0, paceText: t("practiceSummaryNoLaps"), consistencyText: "", justReachedGoals: [], justReachedMilestoneLaps: null, nextGoalTitle: "", nextGoalBody: "" };
|
||
|
||
const paceText = !stats.trendSampleReady || laps < 3
|
||
? t("practiceSummaryPaceInsufficient")
|
||
: (() => {
|
||
const diffMs = Number(stats.previousRecentAverageMs || 0) - Number(currentSession.averageLapMs || 0);
|
||
if (Math.abs(diffMs) < 50) return t("practiceSummaryPaceStable");
|
||
return diffMs > 0
|
||
? t("practiceSummaryPaceFaster", { lap: formatLap(diffMs) })
|
||
: t("practiceSummaryPaceSlower", { lap: formatLap(Math.abs(diffMs)) });
|
||
})();
|
||
|
||
const consistencyText = !currentSession.consistencySampleReady
|
||
? t("practiceSummaryConsistencyInsufficient")
|
||
: (() => {
|
||
const pct = Number(currentSession.consistencySpreadPct || 0);
|
||
const key = pct <= 5 ? "practiceSummaryConsistencyGood" : pct <= 8 ? "practiceSummaryConsistencyOk" : "practiceSummaryConsistencyRough";
|
||
return t(key, { pct: pct.toFixed(1) });
|
||
})();
|
||
|
||
const lapsBeforeSession = Math.max(0, Number(stats.totalLaps || 0) - laps);
|
||
const justReachedGoals = (Array.isArray(goals) ? goals : []).filter((goal) => goal.reached && lapsBeforeSession < goal.targetLaps);
|
||
const milestoneBeforeTarget = nextMilestoneForLaps(lapsBeforeSession);
|
||
const justReachedMilestoneLaps = milestoneBeforeTarget <= Number(stats.totalLaps || 0) ? milestoneBeforeTarget : null;
|
||
|
||
const recommendationText = recommendationCopy(recommendation);
|
||
const useMilestoneAsNextGoal = recommendation?.level === "baseline" && nextMilestone?.remainingLaps;
|
||
const nextGoalTitle = useMilestoneAsNextGoal ? t("reachLaps", { laps: nextMilestone.targetLaps }) : recommendationText.title;
|
||
const nextGoalBody = useMilestoneAsNextGoal ? t("lapsRemaining", { laps: nextMilestone.remainingLaps }) : recommendationText.body;
|
||
|
||
return { laps, paceText, consistencyText, justReachedGoals, justReachedMilestoneLaps, nextGoalTitle, nextGoalBody };
|
||
}
|
||
|
||
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 = {}, exerciseSessionHistory = []) {
|
||
const todayKey = getLocalDayKey(Date.now());
|
||
const today = (Array.isArray(stats?.dailySummaries) ? stats.dailySummaries : []).find((day) => day.dateKey === todayKey);
|
||
const exerciseSessionsToday = (Array.isArray(exerciseSessionHistory) ? exerciseSessionHistory : [])
|
||
.filter((entry) => getLocalDayKey(new Date(entry.completedAt).getTime()) === 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 = [];
|
||
// Completing a guided exercise pass is worth calling out first - it's the thing the driver
|
||
// most deliberately chose to do, not just background pace/consistency drift.
|
||
if (exerciseSessionsToday.length) credits.push(t("exerciseSessionsCredit", { count: exerciseSessionsToday.length }));
|
||
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>`;
|
||
}
|
||
const markerDrafts = new Map();
|
||
|
||
function profileIsBeingEdited() {
|
||
return (root.contains(document.activeElement) && document.activeElement.matches("input, select, textarea"))
|
||
|| Boolean(root.querySelector("#publicTrainingMarkerForm button:disabled"));
|
||
}
|
||
|
||
function renderProfile(data) {
|
||
const previousForm = root.querySelector("#publicTrainingMarkerForm");
|
||
if (previousForm) {
|
||
const values = new FormData(previousForm);
|
||
markerDrafts.set(previousForm.dataset.classId, { type: values.get("type"), note: values.get("note") });
|
||
}
|
||
const openSections = new Set([...root.querySelectorAll("details[data-persist-open][open]")].map((element) => element.dataset.persistOpen));
|
||
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 evenLapsConfig = activeClass?.evenLapsConfig || null;
|
||
const evenLapsProgress = activeClass?.evenLapsProgress || null;
|
||
const evenLapsSuggestedTargetMs = stats.bestLapMs ? Math.round(stats.bestLapMs * 1.05) : 0;
|
||
const evenLapsRun = readExerciseRunState("evenlaps");
|
||
const evenLapsRunning = Boolean(evenLapsRun);
|
||
const stepTrainingConfig = activeClass?.stepTrainingConfig || null;
|
||
const stepTrainingProgress = activeClass?.stepTrainingProgress || null;
|
||
const stepTrainingRun = readExerciseRunState("steptraining");
|
||
const stepTrainingRunning = Boolean(stepTrainingRun);
|
||
const exerciseSessionHistory = activeClass?.exerciseSessionHistory || data.exerciseSessionHistory || [];
|
||
if (evenLapsRun && evenLapsConfig && evenLapsProgress?.currentStreak >= evenLapsConfig.lapCount) {
|
||
void maybeRecordExerciseCompletion("evenLaps", evenLapsRun.startedAt);
|
||
}
|
||
if (stepTrainingRun && stepTrainingProgress?.complete) {
|
||
void maybeRecordExerciseCompletion("stepTraining", stepTrainingRun.startedAt);
|
||
}
|
||
const defaultStepTrainingRows = [
|
||
{ effort: "calm", lapCount: 5 }, { effort: "controlled", lapCount: 5 }, { effort: "fast", lapCount: 5 },
|
||
{ effort: "controlled", lapCount: 5 }, { effort: "calm", lapCount: 5 },
|
||
];
|
||
const stepTrainingFormRows = stepTrainingConfig?.steps?.length
|
||
? [...stepTrainingConfig.steps, ...Array(Math.max(0, 5 - stepTrainingConfig.steps.length)).fill({ effort: "calm", lapCount: 0 })].slice(0, 5)
|
||
: defaultStepTrainingRows;
|
||
const motivation = buildProfileMotivation(stats, channelStats, exerciseSessionHistory);
|
||
const recommendationText = recommendationCopy(recommendation);
|
||
const timerState = readTimerState();
|
||
const timerConfig = getTimerConfig(timerState);
|
||
const timerDurationMs = getTimerDurationMs(timerConfig);
|
||
const timerLocked = Boolean(timerState?.startedAt && getTimerElapsed(timerState) < timerDurationMs);
|
||
const timerJustFinished = Boolean(timerState?.startedAt && getTimerElapsed(timerState) >= timerDurationMs);
|
||
const showPracticeSummary = timerJustFinished && String(timerState.startedAt) !== readPracticeSummaryDismissedFor();
|
||
const practiceSummary = showPracticeSummary ? buildPracticeSummary({ currentSession, stats, goals, recommendation, nextMilestone }) : null;
|
||
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) => {
|
||
const isSessions = goal.metric === "sessions";
|
||
const meta = exerciseKindMeta(goal.exerciseKind);
|
||
const unitSuffix = isSessions ? ` ${meta.emoji} ${escapeHtml(t(meta.titleKey))}` : "";
|
||
return `
|
||
<article class="profile-goal ${goal.reached ? "reached" : ""}">
|
||
<div class="profile-goal-row">
|
||
<strong>${escapeHtml(goal.title || (isSessions ? t("reachSessions", { count: goal.targetLaps }) : t("reachLaps", { laps: goal.targetLaps })))}</strong>
|
||
<span>${goal.currentLaps} / ${goal.targetLaps}${unitSuffix}</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 paceBuckets = Array.isArray(stats.paceBuckets) ? stats.paceBuckets : [];
|
||
const paceBucketMarkup = paceBuckets.length ? paceBuckets.map((bucket) => `<article><span>${escapeHtml(new Date(bucket.startTs).toLocaleString(language, { dateStyle: "short", timeStyle: "short" }))}</span><strong>${formatLap(bucket.paceMs)}</strong><small>${escapeHtml(t("blockLaps", { laps: bucket.lapCount }))} · PB ${formatLap(bucket.bestLapMs)}${bucket.markerCount ? " · " + escapeHtml(t("blockMarkers", { count: bucket.markerCount })) : ""}</small></article>`).join("") : `<p class="profile-empty">-</p>`;
|
||
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>` : ""}
|
||
${renderLayoutSelect(data.trackLayouts)}
|
||
${renderSourceSelect(data.lapSource)}
|
||
</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>
|
||
|
||
${practiceSummary ? `
|
||
<section class="profile-card profile-summary-card" style="margin-top:14px">
|
||
<div class="profile-card-head"><h2>${escapeHtml(t("practiceSummaryTitle"))}</h2></div>
|
||
<div class="profile-card-body">
|
||
${practiceSummary.laps ? `
|
||
<div class="profile-session-heading">${escapeHtml(t("sessionLaps"))}: ${practiceSummary.laps}</div>
|
||
<p>${escapeHtml(practiceSummary.paceText)}</p>
|
||
<p>${escapeHtml(practiceSummary.consistencyText)}</p>
|
||
${practiceSummary.justReachedMilestoneLaps ? `<p class="profile-summary-highlight">${escapeHtml(t("practiceSummaryMilestoneReached", { laps: practiceSummary.justReachedMilestoneLaps }))}</p>` : ""}
|
||
${practiceSummary.justReachedGoals.map((goal) => `
|
||
<p class="profile-summary-highlight">${escapeHtml(t("practiceSummaryGoalReached", { title: goal.title || t("reachLaps", { laps: goal.targetLaps }), laps: goal.targetLaps }))}</p>
|
||
${goal.reward ? `<p class="profile-summary-reward">${escapeHtml(t("practiceSummaryRewardHint", { reward: goal.reward }))}</p>` : ""}
|
||
`).join("")}
|
||
<div class="profile-summary-next-goal">
|
||
<span class="profile-mini-label">${escapeHtml(t("practiceSummaryNextGoalTitle"))}</span>
|
||
<h3>${escapeHtml(practiceSummary.nextGoalTitle)}</h3>
|
||
<p class="profile-plan-copy">${escapeHtml(practiceSummary.nextGoalBody)}</p>
|
||
</div>
|
||
` : `<p class="profile-empty">${escapeHtml(practiceSummary.paceText)}</p>`}
|
||
<div class="profile-actions">
|
||
<button id="profileSummaryClose" class="profile-button" type="button">${escapeHtml(t("practiceSummaryClose"))}</button>
|
||
</div>
|
||
</div>
|
||
</section>
|
||
` : ""}
|
||
|
||
<section class="profile-card profile-exercise-card" style="margin-top:14px">
|
||
<div class="profile-card-head"><div><span class="profile-mini-label">${escapeHtml(t("evenLapsEyebrow"))}</span><h2>${escapeHtml(t("evenLapsTitle"))}</h2></div></div>
|
||
<div class="profile-card-body">
|
||
${evenLapsConfig && evenLapsProgress?.active ? `
|
||
<div class="profile-session-heading">
|
||
${escapeHtml(evenLapsProgress.currentStreak > 0
|
||
? t("evenLapsStreak", { current: evenLapsProgress.currentStreak, target: evenLapsConfig.lapCount })
|
||
: evenLapsProgress.bestStreakToday > 0
|
||
? t("evenLapsNewStreak")
|
||
: t("evenLapsStartHint"))}
|
||
</div>
|
||
<div class="profile-session-stats">
|
||
<div><span>${escapeHtml(t("evenLapsBestTodayLabel"))}</span><strong>${evenLapsProgress.bestStreakToday}</strong></div>
|
||
${evenLapsProgress.lastLapMs != null ? `<div><span>${escapeHtml(t("sessionLaps"))}</span><strong class="${evenLapsProgress.lastLapWithinTolerance ? "is-positive" : "is-negative"}">${formatLap(evenLapsProgress.lastLapMs)}</strong></div>` : ""}
|
||
</div>
|
||
` : `<p class="profile-empty">${escapeHtml(evenLapsConfig ? t("evenLapsNotStarted") : t("evenLapsHint"))}</p>`}
|
||
<fieldset id="profileEvenLapsSetup" class="profile-timer-setup">
|
||
<legend>${escapeHtml(t("evenLapsHint"))}</legend>
|
||
<label><span>${escapeHtml(t("evenLapsTargetLabel"))}</span><input id="profileEvenLapsTarget" type="number" min="0.1" step="0.1" value="${evenLapsConfig ? (evenLapsConfig.targetMs / 1000).toFixed(1) : evenLapsSuggestedTargetMs ? (evenLapsSuggestedTargetMs / 1000).toFixed(1) : ""}" placeholder="${evenLapsSuggestedTargetMs ? (evenLapsSuggestedTargetMs / 1000).toFixed(1) : ""}" /></label>
|
||
<label><span>${escapeHtml(t("evenLapsToleranceLabel"))}</span><input id="profileEvenLapsTolerance" type="number" min="0.1" step="0.1" value="${evenLapsConfig ? (evenLapsConfig.toleranceMs / 1000).toFixed(1) : "0.5"}" /></label>
|
||
<label><span>${escapeHtml(t("evenLapsLapCountLabel"))}</span><input id="profileEvenLapsLapCount" type="number" min="1" step="1" value="${evenLapsConfig ? evenLapsConfig.lapCount : 5}" /></label>
|
||
</fieldset>
|
||
${evenLapsSuggestedTargetMs && !evenLapsConfig ? `<small>${escapeHtml(t("evenLapsSuggestionHint", { lap: formatLap(evenLapsSuggestedTargetMs) }))}</small>` : ""}
|
||
<div class="profile-actions">
|
||
<button id="profileEvenLapsSave" class="profile-button" type="button">${escapeHtml(t("saveSetup"))}</button>
|
||
<button id="profileEvenLapsStart" class="profile-button profile-button-primary" type="button" ${evenLapsRunning ? "disabled" : ""}>${escapeHtml(t("start"))}</button>
|
||
<button id="profileEvenLapsStop" class="profile-button" type="button" ${evenLapsRunning ? "" : "disabled"}>${escapeHtml(t("stop"))}</button>
|
||
</div>
|
||
</div>
|
||
</section>
|
||
|
||
<section class="profile-card profile-exercise-card" style="margin-top:14px">
|
||
<div class="profile-card-head"><div><span class="profile-mini-label">${escapeHtml(t("stepTrainingEyebrow"))}</span><h2>${escapeHtml(t("stepTrainingTitle"))}</h2></div></div>
|
||
<div class="profile-card-body">
|
||
${stepTrainingConfig && stepTrainingProgress?.active ? `
|
||
${stepTrainingProgress.complete
|
||
? `<div class="profile-session-heading"><strong>${escapeHtml(t("stepTrainingComplete"))}</strong></div>`
|
||
: stepTrainingProgress.currentStep
|
||
? `<div class="profile-session-heading">
|
||
${escapeHtml(t("stepTrainingCurrent", { step: stepTrainingProgress.currentStepIndex + 1, total: stepTrainingProgress.totalSteps, effort: t(`effort${stepTrainingProgress.currentStep.effort.charAt(0).toUpperCase()}${stepTrainingProgress.currentStep.effort.slice(1)}`) }))}
|
||
<strong>${escapeHtml(t("stepTrainingRemaining", { laps: stepTrainingProgress.currentStep.lapsRemaining }))}</strong>
|
||
</div>`
|
||
: ""}
|
||
<div class="profile-step-pills">
|
||
${stepTrainingProgress.steps.map((step) => `
|
||
<span class="profile-step-pill ${step.done ? "is-done" : step.index === stepTrainingProgress.currentStepIndex ? "is-current" : ""}">
|
||
${escapeHtml(t(`effort${step.effort.charAt(0).toUpperCase()}${step.effort.slice(1)}`))} · ${step.lapsCompleted}/${step.lapCount}
|
||
</span>
|
||
`).join("")}
|
||
</div>
|
||
${stepTrainingProgress.controlledComparison ? `
|
||
<small>${escapeHtml(t("stepTrainingCompare", {
|
||
first: formatLap(stepTrainingProgress.controlledComparison.firstAvgMs),
|
||
last: formatLap(stepTrainingProgress.controlledComparison.lastAvgMs),
|
||
diff: `${stepTrainingProgress.controlledComparison.diffMs >= 0 ? "+" : ""}${(stepTrainingProgress.controlledComparison.diffMs / 1000).toFixed(2)}s`,
|
||
}))}</small>
|
||
` : ""}
|
||
` : `<p class="profile-empty">${escapeHtml(stepTrainingConfig ? t("stepTrainingNotStarted") : t("stepTrainingHint"))}</p>`}
|
||
<div class="profile-steptraining-form">
|
||
${stepTrainingFormRows.map((row, index) => `
|
||
<div class="profile-steptraining-row">
|
||
<select id="profileStepEffort${index}">
|
||
<option value="calm" ${row.effort === "calm" ? "selected" : ""}>${escapeHtml(t("effortCalm"))}</option>
|
||
<option value="controlled" ${row.effort === "controlled" ? "selected" : ""}>${escapeHtml(t("effortControlled"))}</option>
|
||
<option value="fast" ${row.effort === "fast" ? "selected" : ""}>${escapeHtml(t("effortFast"))}</option>
|
||
</select>
|
||
<input id="profileStepLaps${index}" type="number" min="0" step="1" value="${row.lapCount || ""}" placeholder="0" />
|
||
</div>
|
||
`).join("")}
|
||
</div>
|
||
<div class="profile-actions">
|
||
<button id="profileStepTrainingSave" class="profile-button" type="button">${escapeHtml(t("saveSetup"))}</button>
|
||
<button id="profileStepTrainingStart" class="profile-button profile-button-primary" type="button" ${stepTrainingRunning ? "disabled" : ""}>${escapeHtml(t("start"))}</button>
|
||
<button id="profileStepTrainingStop" class="profile-button" type="button" ${stepTrainingRunning ? "" : "disabled"}>${escapeHtml(t("stop"))}</button>
|
||
</div>
|
||
</div>
|
||
</section>
|
||
|
||
<details class="profile-card profile-disclosure profile-performance ${visibility.performance ? "" : "is-hidden"}" data-persist-open="performance" ${openSections.has("performance") ? "open" : ""} style="margin-top:14px">
|
||
<summary class="profile-card-head"><h2>${escapeHtml(t("performance"))}</h2><span>+</span></summary>
|
||
<form id="publicTrainingMarkerForm" class="profile-marker-form" data-class-id="${escapeHtml(selectedClassId)}">
|
||
<div><h3>${escapeHtml(t("markerTitle"))}</h3><p>${escapeHtml(t("markerHint"))}</p></div>
|
||
<label><span>${escapeHtml(t("markerType"))}</span><select name="type"><option value="setup">${escapeHtml(t("markerSetup"))}</option><option value="tires">${escapeHtml(t("markerTires"))}</option><option value="suspension">${escapeHtml(t("markerSuspension"))}</option><option value="car">${escapeHtml(t("markerCar"))}</option><option value="note">${escapeHtml(t("markerNoteType"))}</option></select></label>
|
||
<label><span>${escapeHtml(t("markerNote"))}</span><input name="note" maxlength="160" /></label>
|
||
<button class="profile-button profile-button-primary" type="submit">${escapeHtml(t("markerSave"))}</button>
|
||
<small id="publicTrainingMarkerStatus"></small>
|
||
</form>
|
||
<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-pace-blocks"><h3>${escapeHtml(t("paceBlocks"))}</h3><p>${escapeHtml(t("paceBlocksHint"))}</p><div>${paceBucketMarkup}</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"}" data-persist-open="history" ${openSections.has("history") ? "open" : ""} 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>
|
||
|
||
<details class="profile-card profile-disclosure ${visibility.history ? "" : "is-hidden"}" data-persist-open="exerciseHistory" ${openSections.has("exerciseHistory") ? "open" : ""} style="margin-top:14px">
|
||
<summary class="profile-card-head"><h2>${escapeHtml(t("exerciseHistoryTitle"))}</h2><span>+</span></summary>
|
||
<div class="profile-card-body">
|
||
<p class="hint">${escapeHtml(t("exerciseHistoryHint"))}</p>
|
||
${exerciseSessionHistory.length ? `
|
||
<ul class="profile-exercise-history">
|
||
${exerciseSessionHistory.map((entry) => {
|
||
const meta = exerciseKindMeta(entry.kind);
|
||
const date = new Date(entry.completedAt).toLocaleString(language, { dateStyle: "short", timeStyle: "short" });
|
||
const detail = entry.kind === "evenLaps"
|
||
? t("exerciseHistoryEvenLaps", { streak: entry.summary?.streak ?? "-", lap: formatLap(entry.summary?.targetMs) })
|
||
: entry.kind === "stepTraining"
|
||
? t("exerciseHistoryStepTraining", { steps: entry.summary?.totalSteps ?? "-", laps: entry.summary?.totalLaps ?? "-" })
|
||
: t("exerciseHistoryTimer", { laps: entry.summary?.laps ?? "-", lap: formatLap(entry.summary?.averageLapMs) });
|
||
return `
|
||
<li class="profile-exercise-history-row">
|
||
<span class="profile-exercise-history-emoji">${meta.emoji}</span>
|
||
<div>
|
||
<strong>${escapeHtml(t(meta.titleKey))}</strong>
|
||
<small>${escapeHtml(date)} · ${escapeHtml(detail)}</small>
|
||
</div>
|
||
</li>
|
||
`;
|
||
}).join("")}
|
||
</ul>
|
||
` : `<p class="profile-empty">${escapeHtml(t("exerciseHistoryEmpty"))}</p>`}
|
||
</div>
|
||
</details>
|
||
`;
|
||
const markerForm = document.getElementById("publicTrainingMarkerForm");
|
||
const draft = markerDrafts.get(selectedClassId);
|
||
if (markerForm && draft) {
|
||
markerForm.elements.namedItem("type").value = draft.type;
|
||
markerForm.elements.namedItem("note").value = draft.note;
|
||
}
|
||
document.getElementById("publicTrainingMarkerForm")?.addEventListener("submit", async (event) => {
|
||
event.preventDefault();
|
||
const form = event.currentTarget;
|
||
const status = document.getElementById("publicTrainingMarkerStatus");
|
||
const button = form.querySelector("button");
|
||
if (button) button.disabled = true;
|
||
try {
|
||
const values = new FormData(form);
|
||
const response = await fetch("/public-training/api/" + encodeURIComponent(shareToken) + "/markers", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ classId: selectedClassId, type: values.get("type"), note: values.get("note") }) });
|
||
if (!response.ok) throw new Error("HTTP " + response.status);
|
||
if (status) status.textContent = t("markerSaved");
|
||
form.reset();
|
||
await loadProfile();
|
||
} catch {
|
||
if (status) status.textContent = t("markerError");
|
||
} finally {
|
||
if (button) button.disabled = false;
|
||
}
|
||
});
|
||
document.getElementById("profileLayout")?.addEventListener("change", (event) => {
|
||
selectedLayout = String(event.currentTarget.value || "current");
|
||
const nextUrl = new URL(window.location.href);
|
||
if (selectedLayout !== "current") nextUrl.searchParams.set("layout", selectedLayout);
|
||
else nextUrl.searchParams.delete("layout");
|
||
window.history.replaceState({}, "", nextUrl);
|
||
loadProfile();
|
||
});
|
||
document.getElementById("profileSource")?.addEventListener("change", (event) => {
|
||
selectedSource = String(event.currentTarget.value || "practice");
|
||
const nextUrl = new URL(window.location.href);
|
||
if (selectedSource !== "practice") nextUrl.searchParams.set("source", selectedSource);
|
||
else nextUrl.searchParams.delete("source");
|
||
window.history.replaceState({}, "", nextUrl);
|
||
loadProfile();
|
||
});
|
||
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();
|
||
bindExerciseControls();
|
||
}
|
||
|
||
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"}`;
|
||
}
|
||
|
||
// Remembers which timer session (identified by its startedAt) the driver has already
|
||
// dismissed the practice summary for, so it doesn't reappear on every later reload of the
|
||
// same finished session, but naturally shows again once a new session starts and finishes.
|
||
function getPracticeSummaryStorageKey() {
|
||
return `rc-training-practice-summary-dismissed:${shareToken}:${selectedClassId || "default"}`;
|
||
}
|
||
|
||
function readPracticeSummaryDismissedFor() {
|
||
try {
|
||
return localStorage.getItem(getPracticeSummaryStorageKey()) || "";
|
||
} catch {
|
||
return "";
|
||
}
|
||
}
|
||
|
||
function writePracticeSummaryDismissedFor(startedAtValue) {
|
||
try {
|
||
if (startedAtValue) localStorage.setItem(getPracticeSummaryStorageKey(), String(startedAtValue));
|
||
else localStorage.removeItem(getPracticeSummaryStorageKey());
|
||
} catch {}
|
||
}
|
||
|
||
// Remembers which run (by startedAt) of each of the three exercise kinds has already had a
|
||
// completion request sent for it, so a background re-render (this function runs on every
|
||
// renderProfile(), not just once) doesn't keep re-POSTing while the completed state persists.
|
||
function getExerciseRecordedStorageKey(kind) {
|
||
return `rc-training-${kind}-recorded:${shareToken}:${selectedClassId || "default"}`;
|
||
}
|
||
|
||
function readExerciseRecordedFor(kind) {
|
||
try {
|
||
return localStorage.getItem(getExerciseRecordedStorageKey(kind)) || "";
|
||
} catch {
|
||
return "";
|
||
}
|
||
}
|
||
|
||
function writeExerciseRecordedFor(kind, startedAtValue) {
|
||
try {
|
||
localStorage.setItem(getExerciseRecordedStorageKey(kind), String(startedAtValue));
|
||
} catch {}
|
||
}
|
||
|
||
// The driver's browser only ever *asks* the server to record a completion - the server
|
||
// independently recomputes the outcome from real ledger laps and refuses if it disagrees (see
|
||
// recordPublicExerciseSession in server/public_training_profile.js). This just avoids sending
|
||
// that request more than once per run.
|
||
async function maybeRecordExerciseCompletion(kind, startedAt, extra = {}) {
|
||
if (!startedAt || !selectedClassId) return;
|
||
if (readExerciseRecordedFor(kind) === String(startedAt)) return;
|
||
writeExerciseRecordedFor(kind, startedAt);
|
||
try {
|
||
const response = await fetch(`/public-training/api/${encodeURIComponent(shareToken)}/exercise-sessions`, {
|
||
method: "POST",
|
||
headers: { "Content-Type": "application/json" },
|
||
body: JSON.stringify({ classId: selectedClassId, kind, startedAgoMs: Math.max(0, Date.now() - startedAt), ...extra }),
|
||
});
|
||
if (response.ok) await loadProfile();
|
||
} catch {
|
||
// best-effort - a missed credit for one session is not worth retry complexity here
|
||
}
|
||
}
|
||
|
||
// The two guided exercises track progress by laps completed since the driver tapped
|
||
// "start", not by elapsed time, so unlike the timer above there is no pause/duration to
|
||
// manage locally - just a start timestamp (or none) per class, mirrored to the server as
|
||
// "started ago" on each poll so it can compute the sanitized streak/step progress.
|
||
function getExerciseRunStorageKey(kind) {
|
||
return `rc-training-${kind}-run:${shareToken}:${selectedClassId || "default"}`;
|
||
}
|
||
|
||
function readExerciseRunState(kind) {
|
||
try {
|
||
const parsed = JSON.parse(localStorage.getItem(getExerciseRunStorageKey(kind)) || "null");
|
||
return parsed && typeof parsed === "object" && parsed.startedAt ? parsed : null;
|
||
} catch {
|
||
return null;
|
||
}
|
||
}
|
||
|
||
function writeExerciseRunState(kind, value) {
|
||
const key = getExerciseRunStorageKey(kind);
|
||
if (value) localStorage.setItem(key, JSON.stringify(value));
|
||
else localStorage.removeItem(key);
|
||
}
|
||
|
||
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();
|
||
});
|
||
document.getElementById("profileSummaryClose")?.addEventListener("click", () => {
|
||
const current = readTimerState();
|
||
writePracticeSummaryDismissedFor(current?.startedAt || "");
|
||
renderProfile(profileData);
|
||
});
|
||
startTimerLoop();
|
||
}
|
||
|
||
function bindExerciseControls() {
|
||
document.getElementById("profileEvenLapsSave")?.addEventListener("click", async () => {
|
||
const targetMs = Math.round(Number(document.getElementById("profileEvenLapsTarget")?.value || 0) * 1000);
|
||
const toleranceMs = Math.round(Number(document.getElementById("profileEvenLapsTolerance")?.value || 0) * 1000);
|
||
const lapCount = Math.max(1, Math.round(Number(document.getElementById("profileEvenLapsLapCount")?.value || 0) || 5));
|
||
if (!(targetMs > 0) || !(toleranceMs >= 0)) return;
|
||
const button = document.getElementById("profileEvenLapsSave");
|
||
if (button) button.disabled = true;
|
||
try {
|
||
await fetch(`/public-training/api/${encodeURIComponent(shareToken)}/even-laps`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ classId: selectedClassId, targetMs, toleranceMs, lapCount }) });
|
||
await loadProfile();
|
||
} finally {
|
||
if (button) button.disabled = false;
|
||
}
|
||
});
|
||
document.getElementById("profileEvenLapsStart")?.addEventListener("click", () => {
|
||
writeExerciseRunState("evenlaps", { startedAt: Date.now() });
|
||
void loadProfile();
|
||
});
|
||
document.getElementById("profileEvenLapsStop")?.addEventListener("click", () => {
|
||
writeExerciseRunState("evenlaps", null);
|
||
void loadProfile();
|
||
});
|
||
|
||
document.getElementById("profileStepTrainingSave")?.addEventListener("click", async () => {
|
||
const steps = [0, 1, 2, 3, 4]
|
||
.map((index) => ({
|
||
effort: String(document.getElementById(`profileStepEffort${index}`)?.value || "calm"),
|
||
lapCount: Math.max(0, Math.round(Number(document.getElementById(`profileStepLaps${index}`)?.value || 0) || 0)),
|
||
}))
|
||
.filter((step) => step.lapCount > 0);
|
||
if (!steps.length) return;
|
||
const button = document.getElementById("profileStepTrainingSave");
|
||
if (button) button.disabled = true;
|
||
try {
|
||
await fetch(`/public-training/api/${encodeURIComponent(shareToken)}/step-training`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ classId: selectedClassId, steps }) });
|
||
await loadProfile();
|
||
} finally {
|
||
if (button) button.disabled = false;
|
||
}
|
||
});
|
||
document.getElementById("profileStepTrainingStart")?.addEventListener("click", () => {
|
||
writeExerciseRunState("steptraining", { startedAt: Date.now() });
|
||
void loadProfile();
|
||
});
|
||
document.getElementById("profileStepTrainingStop")?.addEventListener("click", () => {
|
||
writeExerciseRunState("steptraining", null);
|
||
void loadProfile();
|
||
});
|
||
}
|
||
|
||
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"));
|
||
const justFinished = phaseName === "finished";
|
||
// Update the reentrancy guard before triggering a render: renderProfile() calls back
|
||
// into updateTimerDisplay() synchronously (see below), which would otherwise see the
|
||
// stale lastTimerPhase, take this branch again, and recurse without end.
|
||
lastTimerPhase = phaseName;
|
||
if (justFinished) {
|
||
speak(t("finishCue"));
|
||
void maybeRecordExerciseCompletion("timer", state.startedAt, { windowMs: timerDurationMs });
|
||
// Show the practice summary the moment the pass actually finishes, rather than
|
||
// waiting for the next background poll (up to 10s away) to pick it up.
|
||
if (profileData) renderProfile(profileData);
|
||
}
|
||
}
|
||
}
|
||
|
||
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);
|
||
}
|
||
|
||
const profileConnection = { lastSuccessAt: null, failed: false, loading: false };
|
||
|
||
function getProfileConnectionState(now = Date.now()) {
|
||
if (profileConnection.failed) return "failed";
|
||
if (profileConnection.lastSuccessAt !== null && now - profileConnection.lastSuccessAt >= 30000) return "stale";
|
||
return profileConnection.lastSuccessAt === null ? "loading" : "current";
|
||
}
|
||
|
||
function updateProfileConnectionStatus() {
|
||
const status = document.getElementById("publicTrainingConnection");
|
||
const label = document.getElementById("publicTrainingConnectionText");
|
||
const retry = document.getElementById("publicTrainingRetry");
|
||
if (!status || !label || !retry) return;
|
||
const state = getProfileConnectionState();
|
||
status.dataset.state = state;
|
||
const last = profileConnection.lastSuccessAt;
|
||
const text = t(`connection_${state}`) + (last === null ? "" : " " + t("connection_last", { time: new Date(last).toLocaleTimeString(language) }));
|
||
if (label.textContent !== text) label.textContent = text;
|
||
retry.textContent = t(profileConnection.loading ? "connection_retrying" : "connection_retry");
|
||
retry.hidden = state === "current" || (state === "loading" && !profileConnection.failed);
|
||
retry.disabled = profileConnection.loading;
|
||
}
|
||
|
||
// Only shown once the club has set up track layouts. Pace/best/consistency follow the
|
||
// choice; lifetime totals always cover every lap.
|
||
function renderLayoutSelect(trackLayouts) {
|
||
const options = Array.isArray(trackLayouts?.options) ? trackLayouts.options : [];
|
||
if (!options.length) return "";
|
||
const selected = trackLayouts.selected || "current";
|
||
const option = (value, label) => `<option value="${escapeHtml(value)}" ${selected === value ? "selected" : ""}>${escapeHtml(label)}</option>`;
|
||
return `<label class="profile-class-select"><span>${escapeHtml(t("layoutStats"))}</span><select id="profileLayout">
|
||
${option("current", t("layoutCurrent"))}
|
||
${options.slice().reverse().map((item) => option(item.id, item.label)).join("")}
|
||
${trackLayouts.hasUntaggedLaps ? option("none", t("layoutNone")) : ""}
|
||
${option("all", t("layoutAll"))}
|
||
</select></label>`;
|
||
}
|
||
|
||
// Practice by default; race laps (qualifying, heats, finals) only on request.
|
||
function renderSourceSelect(source) {
|
||
const selected = source || "practice";
|
||
const option = (value, label) => `<option value="${value}" ${selected === value ? "selected" : ""}>${escapeHtml(label)}</option>`;
|
||
return `<label class="profile-class-select"><span>${escapeHtml(t("lapSource"))}</span><select id="profileSource">
|
||
${option("practice", t("lapSourcePractice"))}${option("race", t("lapSourceRace"))}${option("all", t("lapSourceAll"))}
|
||
</select></label>`;
|
||
}
|
||
|
||
async function loadProfile(background = false) {
|
||
if (profileConnection.loading || (background && profileIsBeingEdited())) return;
|
||
profileConnection.loading = true;
|
||
updateProfileConnectionStatus();
|
||
const controller = new AbortController();
|
||
const timeout = setTimeout(() => controller.abort(), 15000);
|
||
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 evenLapsRun = readExerciseRunState("evenlaps");
|
||
if (evenLapsRun) apiUrl.searchParams.set("evenLapsStartedAgoMs", String(Math.max(0, Date.now() - evenLapsRun.startedAt)));
|
||
const stepTrainingRun = readExerciseRunState("steptraining");
|
||
if (stepTrainingRun) apiUrl.searchParams.set("stepTrainingStartedAgoMs", String(Math.max(0, Date.now() - stepTrainingRun.startedAt)));
|
||
if (selectedLayout !== "current") apiUrl.searchParams.set("layout", selectedLayout);
|
||
if (selectedSource !== "practice") apiUrl.searchParams.set("source", selectedSource);
|
||
const response = await fetch(apiUrl, { cache: "no-store", signal: controller.signal });
|
||
if (!response.ok) throw new Error(`HTTP ${response.status}`);
|
||
const data = await response.json();
|
||
if (background && profileIsBeingEdited()) return;
|
||
renderProfile(data);
|
||
profileConnection.lastSuccessAt = Date.now();
|
||
profileConnection.failed = false;
|
||
} catch {
|
||
profileConnection.failed = true;
|
||
if (background && profileData) return;
|
||
root.innerHTML = `<section class="public-training-error"><div class="profile-brand-mark">RC</div><h1>${escapeHtml(t("loadError"))}</h1></section>`;
|
||
} finally {
|
||
clearTimeout(timeout);
|
||
profileConnection.loading = false;
|
||
updateProfileConnectionStatus();
|
||
}
|
||
}
|
||
|
||
loadProfile();
|
||
document.getElementById("publicTrainingRetry")?.addEventListener("click", () => loadProfile(true));
|
||
setInterval(updateProfileConnectionStatus, 1000);
|
||
setInterval(() => {
|
||
if (!document.hidden) loadProfile(true);
|
||
}, 10000);
|