TrackingWorkout / index.html
BitDown's picture
Update index.html
d0a3ba3 verified
raw
history blame
39.2 kB
<!DOCTYPE html>
<html lang="fr">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>LiftTrack - Suivi Musculation Multi-Utilisateurs</title>
<style>
/* --- Styles existants (raccourcis pour la lisibilité) --- */
:root {
--bg-dark: #121212;
--bg-card: #1e1e1e;
--text-light: #e0e0e0;
--accent: #4CAF50;
--accent-dark: #3a8a3d;
--danger: #f44336;
}
* { margin: 0; padding: 0; box-sizing: border-box; font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; }
body { background-color: var(--bg-dark); color: var(--text-light); min-height: 100vh; padding-bottom: 80px; }
.container { width: 100%; max-width: 800px; margin: 0 auto; padding: 1rem; }
header { padding: 1rem 0; text-align: center; border-bottom: 1px solid #333; margin-bottom: 1rem; }
h1, h2, h3 { color: var(--accent); }
.btn { background-color: var(--accent); color: white; border: none; padding: 0.6rem 1.2rem; border-radius: 4px; cursor: pointer; font-weight: bold; transition: background-color 0.2s; }
.btn:hover { background-color: var(--accent-dark); }
.btn-outline { background-color: transparent; color: var(--accent); border: 1px solid var(--accent); }
.btn-danger { background-color: var(--danger); }
input, select, textarea { width: 100%; padding: 0.6rem; margin-bottom: 1rem; background-color: #2a2a2a; border: 1px solid #444; border-radius: 4px; color: var(--text-light); }
input[type="checkbox"] { width: auto; margin-right: 0.5rem; }
.card { background-color: var(--bg-card); border-radius: 8px; padding: 1rem; margin-bottom: 1rem; box-shadow: 0 2px 5px rgba(0,0,0,0.2); }
.form-group { margin-bottom: 1rem; }
.form-row { display: flex; gap: 0.5rem; margin-bottom: 0.5rem; }
.form-row > * { flex: 1; margin-bottom: 0; }
label { display: block; margin-bottom: 0.3rem; color: #bbb; }
.exercise { border-left: 3px solid var(--accent); padding-left: 1rem; margin-bottom: 1.5rem; }
.exercise-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 0.5rem; }
.series-container { margin-left: 0.5rem; margin-top: 0.5rem; }
.series { background-color: #252525; padding: 0.7rem; border-radius: 4px; margin-bottom: 0.5rem; }
.nav-bottom { position: fixed; bottom: 0; left: 0; width: 100%; background-color: #1a1a1a; display: flex; justify-content: space-around; padding: 0.7rem 0; box-shadow: 0 -2px 10px rgba(0,0,0,0.3); }
.nav-item { text-align: center; color: #888; text-decoration: none; font-size: 0.85rem; transition: color 0.2s; }
.nav-item.active { color: var(--accent); }
.nav-icon { font-size: 1.4rem; margin-bottom: 0.2rem; }
.workout-card { border-left: 3px solid var(--accent); cursor: pointer; transition: transform 0.2s; }
.workout-card:hover { transform: translateX(5px); }
.workout-header { display: flex; justify-content: space-between; }
.stat-card { text-align: center; padding: 1rem; }
.stat-value { font-size: 1.8rem; color: var(--accent); font-weight: bold; }
.stats-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(130px, 1fr)); gap: 1rem; }
.hidden { display: none; }
#app-container > div:not(.active) { display: none; } /* Hide inactive pages */
#login-page { display: block; } /* Show login initially */
#main-app-content { display: none; } /* Hide main app initially */
.flex-between { display: flex; justify-content: space-between; align-items: center; }
.badge { background-color: var(--accent); color: white; padding: 0.2rem 0.5rem; border-radius: 10px; font-size: 0.8rem; }
.spinner { border: 4px solid rgba(0, 0, 0, 0.1); width: 36px; height: 36px; border-radius: 50%; border-left-color: var(--accent); animation: spin 1s linear infinite; margin: 2rem auto; display: none; }
@keyframes spin { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } }
.exercise-summary { margin: 0.3rem 0; padding: 0.3rem 0; border-bottom: 1px solid #333; }
.satisfaction { display: flex; align-items: center; justify-content: center; flex-direction: column; margin-top: 1rem; }
.satisfaction-value { font-size: 2rem; color: var(--accent); margin-top: 0.5rem; }
@media (max-width: 600px) { .form-row { flex-direction: column; gap: 0; } .container { padding: 0.5rem; } h1 { font-size: 1.5rem; } }
/* Styles pour la page de connexion */
#login-page .card { max-width: 400px; margin: 2rem auto; }
#login-page h2 { text-align: center; margin-bottom: 1.5rem; }
#login-error { color: var(--danger); text-align: center; margin-top: 1rem; display: none; }
.user-info { text-align: right; margin-bottom: 1rem; font-size: 0.9rem; color: #bbb;}
.user-info button { margin-left: 0.5rem; padding: 0.2rem 0.5rem; font-size: 0.8rem; }
</style>
</head>
<body>
<div class="container">
<header>
<h1>LiftTrack</h1>
<p>Suivi de vos séances de musculation</p>
</header>
<!-- Écran de Connexion -->
<div id="login-page">
<div class="card">
<h2>Accès Utilisateur</h2>
<div class="form-group">
<label for="username">Nom d'utilisateur</label>
<input type="text" id="username" placeholder="Entrez votre nom ou pseudo">
</div>
<button id="login-btn" class="btn" style="width: 100%;">Accéder / Créer</button>
<p id="login-error">Nom d'utilisateur invalide.</p>
<p style="font-size: 0.8rem; color: #888; text-align: center; margin-top: 1rem;">
Entrez un nom pour accéder à vos données ou créer un nouvel espace si le nom n'existe pas.
</p>
</div>
</div>
<!-- Contenu Principal de l'Application (initiallement caché) -->
<div id="main-app-content">
<div class="user-info">
Connecté en tant que: <strong id="current-user-display"></strong>
<button id="logout-btn" class="btn btn-outline">Changer d'utilisateur</button>
</div>
<div id="app-container">
<!-- Page Accueil / Liste Séances -->
<div id="home-page" class="active">
<div class="flex-between">
<h2>Mes séances</h2>
<button id="new-workout-btn" class="btn">Nouvelle séance</button>
</div>
<div id="workouts-list" class="workout-list">
<div class="spinner"></div>
<p id="empty-workout-message" class="hidden" style="text-align: center; margin-top: 2rem;">
Aucune séance enregistrée pour cet utilisateur.
</p>
</div>
</div>
<!-- Page Nouvelle Séance -->
<div id="new-workout-page" class="hidden">
<div class="flex-between">
<h2>Nouvelle séance</h2>
<div> <!-- Conteneur pour les boutons -->
<button id="cancel-new-workout-btn" class="btn btn-outline" style="margin-right: 0.5rem;">Annuler</button>
<button id="save-workout-btn" class="btn">Enregistrer</button>
</div>
</div>
<div class="card">
<div class="form-group">
<label for="workout-name">Nom de la séance</label>
<input type="text" id="workout-name" placeholder="Ex: Push, Legs, Full Body...">
</div>
<div class="form-row">
<div class="form-group">
<label for="workout-date">Date</label>
<input type="date" id="workout-date">
</div>
<div class="form-group">
<label for="workout-duration">Durée (min)</label>
<input type="number" id="workout-duration" min="1" placeholder="60">
</div>
</div>
</div>
<h3 style="margin: 1rem 0;">Exercices</h3>
<div id="exercises-container"></div>
<button id="add-exercise-btn" class="btn btn-outline" style="width: 100%; margin-top: 1rem;">+ Ajouter Exercice</button>
<div class="card" style="margin-top: 2rem;">
<div class="form-group">
<label for="satisfaction">Niveau de satisfaction (1-100%)</label>
<input type="range" id="satisfaction" min="1" max="100" value="75">
<div class="satisfaction">
<span>Satisfaction</span>
<div class="satisfaction-value">75%</div>
</div>
</div>
</div>
</div>
<!-- Page Détail Séance -->
<div id="workout-details-page" class="hidden">
<div class="flex-between">
<h2 id="detail-workout-name">Détail Séance</h2>
<button id="back-to-home" class="btn btn-outline">Retour</button>
</div>
<div class="card">
<div class="workout-details-info">
<div class="form-row">
<p><strong>Date:</strong> <span id="detail-date"></span></p>
<p><strong>Durée:</strong> <span id="detail-duration"></span> min</p>
</div>
</div>
</div>
<div class="stats-grid" style="margin-top: 1rem;">
<div class="card stat-card">
<div class="stat-value" id="detail-tonnage">0</div>
<div>Tonnage Total (kg)</div>
</div>
<div class="card stat-card">
<div class="stat-value" id="detail-satisfaction">0%</div>
<div>Satisfaction</div>
</div>
<div class="card stat-card">
<div class="stat-value" id="detail-exercises-count">0</div>
<div>Exercices</div>
</div>
</div>
<h3 style="margin: 1.5rem 0 1rem;">Exercices Réalisés</h3>
<div id="detail-exercises-container"></div>
<button id="delete-workout-btn" class="btn btn-danger" style="width: 100%; margin-top: 2rem;">Supprimer cette séance</button>
</div>
<!-- Page Statistiques -->
<div id="stats-page" class="hidden">
<h2>Statistiques</h2>
<div class="stats-grid">
<div class="card stat-card">
<div class="stat-value" id="stats-workout-count">0</div>
<div>Séances Totales</div>
</div>
<div class="card stat-card">
<div class="stat-value" id="stats-avg-tonnage">0</div>
<div>Tonnage Moyen</div>
</div>
<div class="card stat-card">
<div class="stat-value" id="stats-avg-satisfaction">0%</div>
<div>Satisfaction Moyenne</div>
</div>
</div>
<h3 style="margin: 1.5rem 0 1rem;">Tendances Récentes</h3>
<div class="card">
<p style="text-align: center; margin: 1rem 0;">
Les statistiques détaillées seront affichées après plusieurs séances enregistrées.
</p>
</div>
</div>
</div>
<!-- Menu Navigation Bas -->
<nav class="nav-bottom">
<a href="#" class="nav-item active" data-page="home-page">
<div class="nav-icon">📋</div>
<div>Séances</div>
</a>
<a href="#" class="nav-item" data-page="stats-page">
<div class="nav-icon">📊</div>
<div>Stats</div>
</a>
</nav>
</div>
</div>
<script>
// --- State Variables ---
let workouts = []; // Workouts for the current user
let currentUser = null; // Stores the logged-in username
let currentWorkoutId = null; // For editing/deleting specific workout
// --- DOM Elements ---
const loginPage = document.getElementById('login-page');
const mainAppContent = document.getElementById('main-app-content');
const usernameInput = document.getElementById('username');
const loginBtn = document.getElementById('login-btn');
const loginError = document.getElementById('login-error');
const currentUserDisplay = document.getElementById('current-user-display');
const logoutBtn = document.getElementById('logout-btn');
const appContainer = document.getElementById('app-container');
const navItems = document.querySelectorAll('.nav-item');
const newWorkoutBtn = document.getElementById('new-workout-btn');
const saveWorkoutBtn = document.getElementById('save-workout-btn');
const cancelNewWorkoutBtn = document.getElementById('cancel-new-workout-btn'); // Added cancel button
const addExerciseBtn = document.getElementById('add-exercise-btn');
const exercisesContainer = document.getElementById('exercises-container');
const workoutsList = document.getElementById('workouts-list');
const backToHomeBtn = document.getElementById('back-to-home');
const deleteWorkoutBtn = document.getElementById('delete-workout-btn');
const satisfactionRange = document.getElementById('satisfaction');
const satisfactionValue = document.querySelector('.satisfaction-value');
const emptyWorkoutMessage = document.getElementById('empty-workout-message');
const workoutDateInput = document.getElementById('workout-date'); // For setting date
// --- Initialization ---
document.addEventListener('DOMContentLoaded', () => {
// Check if a user was previously logged in (in this browser session)
// Note: Using sessionStorage means they need to "log in" each time they open the tab/browser.
// You could use localStorage here too for longer persistence, but it's less secure if the computer is shared.
const rememberedUser = sessionStorage.getItem('liftTrackCurrentUser');
if (rememberedUser) {
loginUser(rememberedUser);
} else {
showLoginPage();
}
initEventListeners();
// Set today's date only if the main app is potentially visible
if (currentUser) {
setTodayDate();
}
});
// --- Authentication Functions ---
function showLoginPage() {
loginPage.style.display = 'block';
mainAppContent.style.display = 'none';
loginError.style.display = 'none'; // Hide error on show
usernameInput.value = ''; // Clear input
}
function showApp() {
loginPage.style.display = 'none';
mainAppContent.style.display = 'block';
currentUserDisplay.textContent = currentUser;
setTodayDate(); // Set date when app becomes visible
loadWorkouts(); // Load data for the current user
renderWorkoutsList(); // Display workouts
showPage('home-page'); // Default to home page
updateStats(); // Update stats for the logged-in user
}
function handleLogin() {
const username = usernameInput.value.trim();
if (username) {
loginUser(username);
} else {
loginError.textContent = "Veuillez entrer un nom d'utilisateur.";
loginError.style.display = 'block';
}
}
function loginUser(username) {
currentUser = username;
sessionStorage.setItem('liftTrackCurrentUser', currentUser); // Remember user for the session
showApp();
}
function handleLogout() {
currentUser = null;
sessionStorage.removeItem('liftTrackCurrentUser'); // Forget user
workouts = []; // Clear current workout data from memory
showLoginPage();
}
// --- Data Persistence Functions (User-Specific) ---
function getStorageKey() {
if (!currentUser) return null; // Should not happen if logged in
// IMPORTANT: Make the key safe for localStorage (no weird chars)
const safeUsername = currentUser.replace(/[^a-zA-Z0-9_-]/g, '_');
return `liftTrackData_${safeUsername}`;
}
function loadWorkouts() {
const storageKey = getStorageKey();
if (!storageKey) {
workouts = [];
return;
}
const savedData = localStorage.getItem(storageKey);
workouts = savedData ? JSON.parse(savedData) : [];
console.log(`Loaded ${workouts.length} workouts for user ${currentUser}`);
}
function saveWorkouts() {
const storageKey = getStorageKey();
if (!storageKey) {
console.error("Cannot save, no user logged in.");
return;
}
localStorage.setItem(storageKey, JSON.stringify(workouts));
console.log(`Saved ${workouts.length} workouts for user ${currentUser}`);
}
// --- Event Listeners ---
function initEventListeners() {
loginBtn.addEventListener('click', handleLogin);
logoutBtn.addEventListener('click', handleLogout);
// Prevent form submission if username input is focused and Enter is pressed
usernameInput.addEventListener('keypress', (e) => {
if (e.key === 'Enter') {
e.preventDefault(); // Stop default form submission behavior
handleLogin(); // Trigger login logic
}
});
// Navigation (unchanged logic, just needs to be inside init)
navItems.forEach(item => {
item.addEventListener('click', (e) => {
e.preventDefault();
if (!currentUser) return; // Don't navigate if not logged in
const targetPage = item.getAttribute('data-page');
showPage(targetPage); // Use the existing showPage function
if (targetPage === 'stats-page') {
updateStats();
}
});
});
// New Workout Button (unchanged logic)
newWorkoutBtn.addEventListener('click', () => {
if (!currentUser) return;
showPage('new-workout-page');
clearNewWorkoutForm();
currentWorkoutId = null; // Ensure it's a new workout
});
// Cancel New Workout Button
cancelNewWorkoutBtn.addEventListener('click', () => {
showPage('home-page'); // Go back home without saving
});
// Save Workout Button (logic moved to saveWorkout function)
saveWorkoutBtn.addEventListener('click', saveWorkout);
// Add Exercise Button (logic moved to addExercise function)
addExerciseBtn.addEventListener('click', addExercise);
// Back to Home Button (unchanged logic)
backToHomeBtn.addEventListener('click', () => {
showPage('home-page');
});
// Delete Workout Button (logic moved to deleteWorkout function)
deleteWorkoutBtn.addEventListener('click', deleteWorkout);
// Satisfaction Slider (unchanged logic)
satisfactionRange.addEventListener('input', () => {
satisfactionValue.textContent = `${satisfactionRange.value}%`;
});
}
// --- Core App Logic (Mostly Unchanged, ensure they run only when logged in) ---
function setTodayDate() {
// Check if the element exists before setting the value
if(workoutDateInput) {
const today = new Date().toISOString().split('T')[0];
workoutDateInput.value = today;
}
}
function showPage(pageId) {
// Only change pages if a user is logged in
if (!currentUser) {
showLoginPage(); // Redirect to login if somehow called without user
return;
}
document.querySelectorAll('#app-container > div').forEach(page => {
page.classList.remove('active'); // Use classList for better practice
});
const pageToShow = document.getElementById(pageId);
if (pageToShow) {
pageToShow.classList.add('active');
} else {
console.error(`Page with ID ${pageId} not found.`);
// Optionally default to home page if target not found
document.getElementById('home-page').classList.add('active');
pageId = 'home-page'; // Update pageId for nav highlighting
}
// Update nav highlighting
navItems.forEach(item => {
if (item.getAttribute('data-page') === pageId) {
item.classList.add('active');
} else {
item.classList.remove('active');
}
});
}
function addExercise() {
// Check if user is logged in before allowing interaction
if (!currentUser) return;
const exerciseId = `exercise-${Date.now()}`;
const exerciseDiv = document.createElement('div');
exerciseDiv.className = 'card exercise'; // Added 'card' class for consistency
exerciseDiv.setAttribute('data-exercise-id', exerciseId);
exerciseDiv.innerHTML = `
<div class="exercise-header">
<input type="text" placeholder="Nom Exercice" class="exercise-name" style="margin-bottom: 0;"> <!-- Remove margin-bottom -->
<button class="btn btn-danger remove-exercise" style="padding: 0.3rem 0.6rem; margin-left: 0.5rem;">×</button> <!-- Use × for 'x' -->
</div>
<div class="form-group" style="margin-top: 0.5rem; margin-bottom: 0.5rem;"> <!-- Reduced margin -->
<label style="display: inline-flex; align-items: center; color: #bbb; font-size: 0.9rem;">
<input type="checkbox" class="unilateral-checkbox" style="margin-bottom: 0; margin-right: 0.3rem;"> Unilatéral
</label>
</div>
<div class="series-container">
<!-- Series added here -->
</div>
<button class="btn btn-outline add-series" style="width: 100%; margin-top: 0.5rem; padding: 0.4rem;">+ Ajouter Série</button>
`;
exercisesContainer.appendChild(exerciseDiv);
// Add event listeners for remove/add series (ensure context is correct)
const removeBtn = exerciseDiv.querySelector('.remove-exercise');
removeBtn.addEventListener('click', () => exerciseDiv.remove());
const addSeriesBtn = exerciseDiv.querySelector('.add-series');
const seriesContainer = exerciseDiv.querySelector('.series-container'); // Get container specific to this exercise
addSeriesBtn.addEventListener('click', () => addSeries(seriesContainer)); // Pass the correct container
// Add the first series automatically
addSeries(seriesContainer);
}
function addSeries(container) {
// Check user login
if (!currentUser) return;
const seriesId = `series-${Date.now()}`;
const seriesDiv = document.createElement('div');
seriesDiv.className = 'series'; // Keep original class
seriesDiv.setAttribute('data-series-id', seriesId);
seriesDiv.innerHTML = `
<div class="form-row" style="align-items: flex-end;"> <!-- Align items bottom -->
<div class="form-group" style="flex: 1.5;"> <!-- More space for reps -->
<label style="font-size: 0.8rem;">Reps</label>
<input type="number" class="reps" min="1" placeholder="10" style="padding: 0.4rem;">
</div>
<div class="form-group" style="flex: 1.5;"> <!-- More space for weight -->
<label style="font-size: 0.8rem;">Charge (kg)</label>
<input type="number" class="weight" min="0" step="0.1" placeholder="20" style="padding: 0.4rem;">
</div>
<div class="form-group" style="flex: 1; display: flex; align-items: center; padding-bottom: 0.6rem;"> <!-- Align checkbox -->
<label style="display: inline-flex; align-items: center; color: #bbb; font-size: 0.8rem; margin-bottom: 0;">
<input type="checkbox" class="degressive-checkbox" style="margin-bottom: 0; margin-right: 0.3rem;"> Dégressive
</label>
</div>
<button class="btn btn-danger remove-series" style="padding: 0.3rem 0.6rem; margin-bottom: 0.6rem; flex: 0.5;">×</button>
</div>
`;
container.appendChild(seriesDiv);
// Add remove listener for this specific series
const removeBtn = seriesDiv.querySelector('.remove-series');
removeBtn.addEventListener('click', () => seriesDiv.remove());
}
function saveWorkout() {
// Check user login
if (!currentUser) return;
// Retrieve base data (unchanged)
const workoutName = document.getElementById('workout-name').value.trim();
const workoutDate = document.getElementById('workout-date').value;
const workoutDuration = parseInt(document.getElementById('workout-duration').value) || 0;
const satisfaction = parseInt(document.getElementById('satisfaction').value);
// Validation (unchanged)
if (!workoutName) { alert("Nom de séance requis."); return; }
if (!workoutDate) { alert("Date requise."); return; }
if (workoutDuration <= 0) { alert("Durée invalide."); return; }
// Retrieve exercises (unchanged logic)
const exercises = [];
const exerciseElements = exercisesContainer.querySelectorAll('.exercise');
if (exerciseElements.length === 0) { alert("Ajoutez au moins un exercice."); return; }
let validationFailed = false; // Flag to stop processing if an error occurs
exerciseElements.forEach(exerciseEl => {
if (validationFailed) return; // Stop if previous exercise had an error
const exerciseName = exerciseEl.querySelector('.exercise-name').value.trim();
const isUnilateral = exerciseEl.querySelector('.unilateral-checkbox').checked;
if (!exerciseName) {
alert("Nom requis pour chaque exercice.");
validationFailed = true;
return;
}
const series = [];
const seriesElements = exerciseEl.querySelectorAll('.series');
if (seriesElements.length === 0) {
alert(`Ajoutez au moins une série à l'exercice "${exerciseName}".`);
validationFailed = true;
return;
}
seriesElements.forEach(seriesEl => {
if (validationFailed) return;
const reps = parseInt(seriesEl.querySelector('.reps').value) || 0;
const weight = parseFloat(seriesEl.querySelector('.weight').value) || 0;
const isDegressive = seriesEl.querySelector('.degressive-checkbox').checked;
if (reps <= 0) {
alert(`Nombre de répétitions valide requis pour "${exerciseName}".`);
validationFailed = true;
return;
}
// Allow weight 0 (bodyweight, etc.) but maybe validate if needed
// if (weight < 0) { alert(`Charge valide requise pour "${exerciseName}".`); return; }
series.push({ reps, weight, isDegressive });
});
if (!validationFailed) {
exercises.push({ name: exerciseName, isUnilateral, series });
}
});
// Stop if validation failed during exercise/series loop
if (validationFailed) return;
// Calculate total tonnage (unchanged logic)
let totalTonnage = 0;
exercises.forEach(exercise => {
exercise.series.forEach(serie => {
const weightFactor = exercise.isUnilateral ? 2 : 1;
totalTonnage += serie.reps * serie.weight * weightFactor;
});
});
// Create workout object (unchanged logic)
const workout = {
id: currentWorkoutId || `workout-${Date.now()}`, // Use existing ID if editing
name: workoutName,
date: workoutDate,
duration: workoutDuration,
exercises,
totalTonnage,
satisfaction
};
// Add or update workout in the user's list
const existingIndex = workouts.findIndex(w => w.id === workout.id);
if (existingIndex > -1) {
workouts[existingIndex] = workout; // Update
} else {
workouts.push(workout); // Add new
}
// Save data for the current user
saveWorkouts();
// Go back to home page and refresh list
showPage('home-page');
renderWorkoutsList();
}
function renderWorkoutsList() {
// Check login
if (!currentUser) {
workoutsList.innerHTML = ''; // Clear list if somehow called logged out
emptyWorkoutMessage.classList.remove('hidden');
return;
}
workoutsList.innerHTML = ''; // Clear previous list
if (workouts.length === 0) {
emptyWorkoutMessage.classList.remove('hidden');
return; // Stop if no workouts
}
emptyWorkoutMessage.classList.add('hidden');
// Sort workouts by date (most recent first) (unchanged)
const sortedWorkouts = [...workouts].sort((a, b) => new Date(b.date) - new Date(a.date));
// Generate HTML for each workout card (unchanged, but uses user's `workouts` array)
sortedWorkouts.forEach(workout => {
const workoutDate = new Date(workout.date).toLocaleDateString('fr-FR');
const workoutDiv = document.createElement('div');
workoutDiv.className = 'card workout-card'; // Use class for styling/selection
workoutDiv.setAttribute('data-workout-id', workout.id);
workoutDiv.innerHTML = `
<div class="workout-header">
<h3>${workout.name}</h3>
<div class="badge">${workoutDate}</div>
</div>
<div class="workout-details" style="margin-top: 0.5rem; font-size: 0.9rem; color: #ccc;">
<p><strong>Durée:</strong> ${workout.duration} min | <strong>Exercices:</strong> ${workout.exercises.length}</p>
<p><strong>Tonnage:</strong> ${workout.totalTonnage.toFixed(1)} kg | <strong>Satisfaction:</strong> ${workout.satisfaction}%</p>
</div>
`;
// Add listener to show details on click
workoutDiv.addEventListener('click', () => displayWorkoutDetails(workout.id));
workoutsList.appendChild(workoutDiv);
});
updateStats(); // Update stats after rendering list
}
function displayWorkoutDetails(workoutId) {
// Check login
if (!currentUser) return;
const workout = workouts.find(w => w.id === workoutId);
if (!workout) return; // Workout not found for this user
// Update basic info (unchanged)
document.getElementById('detail-workout-name').textContent = workout.name;
document.getElementById('detail-date').textContent = new Date(workout.date).toLocaleDateString('fr-FR');
document.getElementById('detail-duration').textContent = workout.duration;
document.getElementById('detail-tonnage').textContent = workout.totalTonnage.toFixed(1);
document.getElementById('detail-satisfaction').textContent = `${workout.satisfaction}%`;
document.getElementById('detail-exercises-count').textContent = workout.exercises.length;
// Display exercises (unchanged logic)
const detailExercisesContainer = document.getElementById('detail-exercises-container');
detailExercisesContainer.innerHTML = ''; // Clear previous details
workout.exercises.forEach(exercise => {
const exerciseDiv = document.createElement('div');
exerciseDiv.className = 'card'; // Use card style for each exercise detail
let seriesHtml = '';
exercise.series.forEach((serie, index) => {
const degressiveLabel = serie.isDegressive ? ' <span class="badge" style="background-color: var(--accent-dark);">Dégressive</span>' : '';
const weightFactor = exercise.isUnilateral ? 2 : 1;
const seriesTonnage = serie.reps * serie.weight * weightFactor;
seriesHtml += `
<div class="exercise-summary">
<div class="flex-between" style="font-size: 0.9rem;">
<span>Série ${index + 1}: ${serie.reps} reps × ${serie.weight} kg${degressiveLabel}</span>
<span style="color: #ccc;">(Tonnage: ${seriesTonnage.toFixed(1)} kg)</span>
</div>
</div>
`;
});
const unilateralLabel = exercise.isUnilateral ? ' <span class="badge">Unilatéral</span>' : '';
exerciseDiv.innerHTML = `
<h3 style="font-size: 1.1rem; margin-bottom: 0.5rem;">${exercise.name}${unilateralLabel}</h3>
<div class="series-summary">
${seriesHtml}
</div>
`;
detailExercisesContainer.appendChild(exerciseDiv);
});
// Store ID for potential delete/edit
currentWorkoutId = workoutId;
// Show the details page
showPage('workout-details-page');
}
function deleteWorkout() {
// Check login and if a workout is selected
if (!currentUser || !currentWorkoutId) return;
const confirmDelete = confirm("Êtes-vous sûr de vouloir supprimer cette séance ? Cette action est irréversible.");
if (!confirmDelete) return;
// Filter out the workout to delete from the current user's data
workouts = workouts.filter(w => w.id !== currentWorkoutId);
// Save the updated data for the user
saveWorkouts();
// Go back to home and refresh the list
showPage('home-page');
renderWorkoutsList(); // This will also update stats
}
function clearNewWorkoutForm() {
// Check login
if (!currentUser) return;
document.getElementById('workout-name').value = '';
document.getElementById('workout-duration').value = '';
setTodayDate(); // Reset date
exercisesContainer.innerHTML = ''; // Clear exercises
satisfactionRange.value = 75; // Reset satisfaction
satisfactionValue.textContent = '75%';
currentWorkoutId = null; // Ensure it's treated as new
}
function updateStats() {
// Check login
if (!currentUser) return;
const workoutCount = workouts.length;
document.getElementById('stats-workout-count').textContent = workoutCount;
if (workoutCount === 0) {
document.getElementById('stats-avg-tonnage').textContent = '0';
document.getElementById('stats-avg-satisfaction').textContent = '0%';
return;
}
// Average Tonnage (unchanged)
const totalTonnageAll = workouts.reduce((sum, workout) => sum + workout.totalTonnage, 0);
const avgTonnage = totalTonnageAll / workoutCount;
document.getElementById('stats-avg-tonnage').textContent = avgTonnage.toFixed(1);
// Average Satisfaction (unchanged)
const totalSatisfaction = workouts.reduce((sum, workout) => sum + workout.satisfaction, 0);
const avgSatisfaction = totalSatisfaction / workoutCount;
document.getElementById('stats-avg-satisfaction').textContent = `${Math.round(avgSatisfaction)}%`;
}
</script>
</body>
</html>