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0fbf
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
<!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>