File size: 38,621 Bytes
ddd7255
 
 
 
 
 
840f62b
 
ddd7255
b59ef08
ddd7255
 
 
 
 
 
 
b59ef08
ddd7255
 
840f62b
ddd7255
 
 
 
 
840f62b
ddd7255
840f62b
ddd7255
 
840f62b
ddd7255
 
840f62b
 
ddd7255
840f62b
 
 
 
 
 
 
 
 
 
ddd7255
840f62b
ddd7255
 
 
 
 
 
 
 
 
 
 
 
840f62b
 
 
 
 
ddd7255
b59ef08
ddd7255
 
 
 
 
 
840f62b
b59ef08
840f62b
 
 
 
 
 
 
 
 
 
 
ddd7255
 
 
 
 
 
840f62b
 
 
 
 
 
 
 
 
b59ef08
840f62b
 
 
 
 
 
ddd7255
 
 
 
 
 
 
 
 
 
 
840f62b
ddd7255
 
 
 
 
 
 
 
 
 
 
 
 
840f62b
ddd7255
 
 
 
 
 
d0a3ba3
 
 
840f62b
d0a3ba3
 
a9f0fbf
ddd7255
840f62b
d0a3ba3
840f62b
d0a3ba3
a9f0fbf
 
d0a3ba3
840f62b
1bef68b
d0a3ba3
840f62b
 
d0a3ba3
840f62b
a9f0fbf
 
840f62b
ddd7255
840f62b
 
d0a3ba3
840f62b
d0a3ba3
840f62b
 
 
 
 
 
 
ddd7255
 
 
840f62b
 
 
d0a3ba3
840f62b
a9f0fbf
 
d0a3ba3
840f62b
1bef68b
840f62b
 
 
d0a3ba3
840f62b
d0a3ba3
a9f0fbf
d0a3ba3
840f62b
1bef68b
840f62b
 
d0a3ba3
840f62b
a9f0fbf
ddd7255
 
 
840f62b
 
 
ddd7255
 
 
840f62b
 
 
b59ef08
 
ddd7255
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b59ef08
 
ddd7255
 
 
 
 
 
840f62b
 
 
ddd7255
 
 
 
840f62b
ddd7255
 
 
840f62b
b59ef08
 
 
 
 
 
 
840f62b
 
 
ddd7255
b59ef08
840f62b
ddd7255
 
 
 
 
 
840f62b
ddd7255
b59ef08
840f62b
ddd7255
 
 
b59ef08
ddd7255
 
840f62b
b59ef08
 
840f62b
 
ddd7255
 
840f62b
ddd7255
 
840f62b
b59ef08
ddd7255
840f62b
 
b59ef08
ddd7255
b59ef08
 
 
 
 
840f62b
ddd7255
840f62b
 
 
 
ddd7255
 
840f62b
ddd7255
 
 
b59ef08
ddd7255
 
b59ef08
ddd7255
 
 
 
 
b59ef08
840f62b
ddd7255
 
b59ef08
ddd7255
840f62b
ddd7255
 
b59ef08
ddd7255
b59ef08
 
840f62b
 
ddd7255
840f62b
 
 
b59ef08
 
 
 
 
840f62b
 
 
ddd7255
 
 
 
b59ef08
840f62b
 
b59ef08
840f62b
 
b59ef08
840f62b
ddd7255
 
b59ef08
840f62b
 
 
 
 
 
b59ef08
 
840f62b
 
 
 
 
 
 
 
b59ef08
 
840f62b
 
 
 
b59ef08
840f62b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ddd7255
840f62b
 
b59ef08
 
 
 
 
 
ddd7255
 
 
 
 
b59ef08
 
 
ddd7255
 
 
 
 
b59ef08
 
 
ddd7255
b59ef08
 
ddd7255
b59ef08
ddd7255
840f62b
b59ef08
840f62b
ddd7255
b59ef08
 
 
 
 
 
 
 
 
 
 
 
 
ddd7255
 
 
b59ef08
ddd7255
 
840f62b
 
 
ddd7255
b59ef08
 
ddd7255
 
 
 
b59ef08
 
ddd7255
 
 
840f62b
ddd7255
 
 
 
 
840f62b
ddd7255
 
 
 
b59ef08
ddd7255
840f62b
b59ef08
840f62b
ddd7255
 
840f62b
ddd7255
 
b59ef08
840f62b
 
 
ddd7255
b59ef08
 
840f62b
ddd7255
840f62b
 
 
ddd7255
 
b59ef08
 
 
ddd7255
b59ef08
 
ddd7255
b59ef08
840f62b
ddd7255
b59ef08
840f62b
 
 
ddd7255
 
b59ef08
840f62b
ddd7255
b59ef08
 
ddd7255
 
 
840f62b
 
ddd7255
 
b59ef08
840f62b
ddd7255
 
b59ef08
840f62b
ddd7255
 
 
 
 
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
<!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>
    <!-- Ajout de la librairie pour les confettis -->
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/confetti.browser.min.js"></script>
    <style>
        /* --- Styles CSS (Superset enlevé) --- */
        :root {
            --bg-dark: #121212;
            --bg-card: #1e1e1e;
            --text-light: #e0e0e0;
            --accent: #4CAF50;
            --accent-dark: #3a8a3d;
            --danger: #f44336;
            /* --superset-border: #4a90e2; enlevé */
        }
        * { 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:disabled { background-color: #555; cursor: not-allowed; }
        .btn-outline { background-color: transparent; color: var(--accent); border: 1px solid var(--accent); }
        .btn-outline:disabled { color: #555; border-color: #555; }
        .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; vertical-align: middle; }
        .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; flex-wrap: wrap; }
        .form-row > * { flex: 1; margin-bottom: 0; min-width: 100px; }
        label { display: block; margin-bottom: 0.3rem; color: #bbb; font-size: 0.9rem; }
        .exercise {
            border-left: 3px solid var(--accent);
            padding-left: 1rem;
            margin-bottom: 1.5rem;
            display: none; /* Caché par défaut, montré par JS */
        }
        .exercise.active-exercise {
            display: block; /* Afficher l'exercice actif */
             animation: fadeIn 0.3s ease-in-out;
        }
        .exercise-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 0.5rem; gap: 0.5rem;}
        .exercise-header input {margin-bottom: 0;}
        .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); z-index: 10; }
        .nav-item { text-align: center; color: #888; text-decoration: none; font-size: 0.85rem; transition: color 0.2s; padding: 0 0.5rem;}
        .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; align-items: flex-start; }
        .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; }
        #login-page { display: block; }
        #main-app-content { display: none; }
        #app-container > div:not(.active) { display: none !important; }
        .flex-between { display: flex; justify-content: space-between; align-items: center; flex-wrap: wrap; gap: 0.5rem;}
        .badge { background-color: var(--accent); color: white; padding: 0.2rem 0.5rem; border-radius: 10px; font-size: 0.8rem; white-space: nowrap; }
        /* .badge-superset enlevé */
        .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; font-size: 0.9rem;}
        .exercise-summary:last-child { border-bottom: none; }
        .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; }
        .exercise-navigation { display: flex; justify-content: space-between; margin-top: 1rem; margin-bottom: 1rem; }
        /* Styles détail superset enlevés */

        /* Animation d'apparition/zoom pour nouvelle séance */
         @keyframes fadeInZoom {
            from { opacity: 0; transform: scale(0.95); }
            to { opacity: 1; transform: scale(1); }
        }
         #new-workout-page.active {
             animation: fadeInZoom 0.3s ease-out;
         }

         /* Styles page de connexion & user info */
        #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 strong { color: var(--text-light); }
        .user-info button { margin-left: 0.5rem; padding: 0.2rem 0.5rem; font-size: 0.8rem; }

         @media (max-width: 600px) {
             .form-row { flex-direction: column; gap: 0; }
             .container { padding: 0.5rem; }
             h1 { font-size: 1.5rem; }
             .flex-between { flex-direction: column; align-items: stretch; }
             .flex-between > div { width: 100%; display: flex; justify-content: flex-end; margin-top: 0.5rem;}
             .user-info { text-align: center; margin-bottom: 0.5rem;}
             .user-info button { display: block; margin: 0.5rem auto 0;}
             .exercise-navigation button { padding: 0.5rem; font-size: 0.9rem;}
         }
        /* Animation fade in standard */
        @keyframes fadeIn {
            from { opacity: 0; }
            to { opacity: 1; }
        }
    </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 -->
        <div id="main-app-content">
            <div class="user-info">
                Connecté: <strong id="current-user-display"></strong>
                <button id="logout-btn" class="btn btn-outline">Changer</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" style="margin-top: 1rem;">
                        <div class="spinner hidden"></div>
                        <p id="empty-workout-message" class="hidden" style="text-align: center; margin-top: 2rem;">
                            Aucune séance enregistrée.
                        </p>
                    </div>
                </div>

                <!-- Page Nouvelle Séance -->
                <div id="new-workout-page">
                     <div class="flex-between">
                        <h2>Nouvelle séance <span id="current-exercise-indicator" style="font-size: 0.9rem; color: #ccc;"></span></h2>
                        <div>
                             <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 Séance</button>
                        </div>
                    </div>
                    <!-- Infos Séance -->
                    <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>
                    <!-- Navigation entre exercices -->
                    <div class="exercise-navigation card">
                        <button id="prev-exercise-btn" class="btn btn-outline">< Précédent</button>
                        <span style="align-self: center; color: #ccc;">Exercice Actif</span>
                        <button id="next-exercise-btn" class="btn btn-outline">Suivant ></button>
                    </div>
                    <!-- Conteneur pour les exercices (un seul visible à la fois) -->
                    <div id="exercises-container">
                        <!-- Exercices ajoutés dynamiquement ici -->
                    </div>
                    <button id="add-exercise-btn" class="btn btn-outline" style="width: 100%; margin-top: 1rem;">+ Ajouter un Nouvel Exercice</button>

                     <!-- Satisfaction -->
                    <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">
                    <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"> <!-- Détails des exercices affichés ici --> </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">
                     <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>
        // --- Variables d'État ---
        let workouts = [];
        let currentUser = null;
        let currentWorkoutId = null;
        let currentExerciseIndex = 0;
        let workoutExercisesForm = []; // Référence aux divs .exercise dans le formulaire

        // --- Éléments DOM ---
        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 spinner = document.querySelector('#workouts-list .spinner');
        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');
        const addExerciseBtn = document.getElementById('add-exercise-btn');
        const exercisesContainer = document.getElementById('exercises-container'); // Conteneur formulaire
        const workoutsList = document.getElementById('workouts-list'); // Conteneur affichage liste
        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');
        const prevExerciseBtn = document.getElementById('prev-exercise-btn');
        const nextExerciseBtn = document.getElementById('next-exercise-btn');
        const currentExerciseIndicator = document.getElementById('current-exercise-indicator');

        // --- Initialisation ---
        document.addEventListener('DOMContentLoaded', () => {
            const rememberedUser = sessionStorage.getItem('liftTrackCurrentUser');
            if (rememberedUser) { loginUser(rememberedUser); } else { showLoginPage(); }
            initEventListeners();
        });

        // --- Authentification & Persistance (inchangées) ---
        function showLoginPage() { loginPage.style.display = 'block'; mainAppContent.style.display = 'none'; loginError.style.display = 'none'; usernameInput.value = ''; currentUser = null; }
        function showApp() { if (!currentUser) return; loginPage.style.display = 'none'; mainAppContent.style.display = 'block'; currentUserDisplay.textContent = currentUser; setTodayDate(); loadWorkouts(); showPage('home-page'); }
        function handleLogin() { const username = usernameInput.value.trim(); if (username && username.length > 0) { loginUser(username); } else { loginError.textContent = "Veuillez entrer un nom d'utilisateur."; loginError.style.display = 'block'; }}
        function loginUser(username) { currentUser = username; sessionStorage.setItem('liftTrackCurrentUser', currentUser); showApp(); }
        function handleLogout() { currentUser = null; sessionStorage.removeItem('liftTrackCurrentUser'); workouts = []; showLoginPage(); }
        function getStorageKey() { if (!currentUser) return null; const safeUsername = currentUser.replace(/[^a-zA-Z0-9_-]/g, '_'); return `liftTrackData_${safeUsername}`; }
        function loadWorkouts() {
             const storageKey = getStorageKey(); if (!storageKey) { workouts = []; return; }
             if (spinner) spinner.classList.remove('hidden'); emptyWorkoutMessage.classList.add('hidden'); workoutsList.innerHTML = '';
             setTimeout(() => { try { const savedData = localStorage.getItem(storageKey); workouts = savedData ? JSON.parse(savedData) : []; console.log(`Chargé ${workouts.length} séances pour ${currentUser}`); } catch (e) { console.error("Erreur parsing localStorage:", e); workouts = []; alert("Erreur chargement données."); } finally { if (spinner) spinner.classList.add('hidden'); renderWorkoutsList(); } }, 150);
        }
        function saveWorkouts() {
             const storageKey = getStorageKey(); if (!storageKey) { console.error("Sauvegarde impossible: non connecté."); return; } try { localStorage.setItem(storageKey, JSON.stringify(workouts)); console.log(`Sauvegardé ${workouts.length} séances pour ${currentUser}`); } catch (e) { console.error("Erreur sauvegarde localStorage:", e); alert("Erreur sauvegarde données."); }
        }

        // --- Écouteurs d'Événements ---
        function initEventListeners() {
            loginBtn.addEventListener('click', handleLogin);
            logoutBtn.addEventListener('click', handleLogout);
            usernameInput.addEventListener('keypress', (e) => { if (e.key === 'Enter') { e.preventDefault(); handleLogin(); } });

            navItems.forEach(item => {
                item.addEventListener('click', (e) => { e.preventDefault(); if (!currentUser) return; const targetPageId = item.getAttribute('data-page'); showPage(targetPageId); navItems.forEach(nav => nav.classList.remove('active')); item.classList.add('active'); if (targetPageId === 'stats-page') { updateStats(); } });
            });

            newWorkoutBtn.addEventListener('click', () => {
                if (!currentUser) return; currentWorkoutId = null; clearNewWorkoutForm(); showPage('new-workout-page');
            });

            cancelNewWorkoutBtn.addEventListener('click', () => showPage('home-page'));
            saveWorkoutBtn.addEventListener('click', saveWorkout);
            addExerciseBtn.addEventListener('click', handleAddNewExercise);
            prevExerciseBtn.addEventListener('click', navigateExerciseForm.bind(null, -1));
            nextExerciseBtn.addEventListener('click', navigateExerciseForm.bind(null, 1));
            backToHomeBtn.addEventListener('click', () => showPage('home-page'));
            deleteWorkoutBtn.addEventListener('click', deleteWorkout);
            satisfactionRange.addEventListener('input', () => { satisfactionValue.textContent = `${satisfactionRange.value}%`; });
        }

        // --- Logique Principale ---
        function setTodayDate() { if(workoutDateInput) { try { const today = new Date().toISOString().split('T')[0]; workoutDateInput.value = today; } catch (e) { console.error("Impossible définir date:", e); workoutDateInput.value = ''; } } }

         function showPage(pageId) {
            if (!currentUser) { showLoginPage(); return; }
            document.querySelectorAll('#app-container > div').forEach(page => page.classList.remove('active'));
            const pageToShow = document.getElementById(pageId);
            if (pageToShow) { pageToShow.classList.add('active'); } else { console.error(`Page ID "${pageId}" non trouvée. Affichage home-page.`); document.getElementById('home-page').classList.add('active'); pageId = 'home-page'; }
            navItems.forEach(item => { item.classList.remove('active'); });
            const activeNavItem = document.querySelector(`.nav-item[data-page="${pageId === 'stats-page' ? 'stats-page' : 'home-page'}"]`);
            if(activeNavItem) activeNavItem.classList.add('active');
            if (pageId === 'new-workout-page') { renderActiveExerciseForm(); }
        }

        // --- Logique Formulaire Nouvelle Séance ---

        function handleAddNewExercise() {
             addExercise(true); // true pour naviguer vers le nouvel exercice
        }

        function addExercise(navigateToNew = false) {
            if (!currentUser) return;
            const exerciseId = `exercise-${Date.now()}`;
            const exerciseDiv = document.createElement('div');
            exerciseDiv.className = 'card exercise';
            exerciseDiv.setAttribute('data-exercise-id', exerciseId);

            // **HTML SANS SUPERSET**
            exerciseDiv.innerHTML = `
                <div class="exercise-header">
                    <input type="text" placeholder="Nom Exercice" class="exercise-name">
                    <button class="btn btn-danger remove-exercise" style="padding: 0.3rem 0.6rem; flex-shrink: 0;">×</button>
                </div>
                <div class="form-group" style="margin-top: 0.5rem; margin-bottom: 0.5rem;">
                     <label style="display: inline-flex; align-items: center; color: #bbb; font-size: 0.9rem;">
                        <input type="checkbox" class="unilateral-checkbox"> Unilatéral
                    </label>
                    <!-- Checkbox Superset enlevée -->
                </div>
                <div class="series-container"></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);

            // Mettre à jour la référence immédiatement
            workoutExercisesForm = Array.from(exercisesContainer.querySelectorAll('.exercise'));

            // Écouteurs pour cet exercice
            const removeBtn = exerciseDiv.querySelector('.remove-exercise');
             removeBtn.addEventListener('click', () => {
                 const indexToRemove = workoutExercisesForm.indexOf(exerciseDiv);
                 if (indexToRemove > -1) {
                     exerciseDiv.remove();
                     workoutExercisesForm = Array.from(exercisesContainer.querySelectorAll('.exercise')); // MAJ après suppression DOM
                     if (currentExerciseIndex >= indexToRemove) { currentExerciseIndex = Math.max(0, currentExerciseIndex - 1); }
                     if (currentExerciseIndex >= workoutExercisesForm.length) { currentExerciseIndex = Math.max(0, workoutExercisesForm.length - 1); }
                     renderActiveExerciseForm();
                 }
             });

            const addSeriesBtn = exerciseDiv.querySelector('.add-series');
            const seriesContainer = exerciseDiv.querySelector('.series-container');
            addSeriesBtn.addEventListener('click', () => addSeries(seriesContainer));

            addSeries(seriesContainer);

             if (navigateToNew) {
                 currentExerciseIndex = workoutExercisesForm.length - 1;
                 renderActiveExerciseForm();
             } else {
                 updateExerciseNavButtons();
             }
        }

        function addSeries(container) {
            if (!currentUser || !container) return; const seriesId = `series-${Date.now()}`; const seriesDiv = document.createElement('div'); seriesDiv.className = 'series'; seriesDiv.setAttribute('data-series-id', seriesId);
            seriesDiv.innerHTML = `<div class="form-row" style="align-items: flex-end; gap: 0.8rem;"> <div class="form-group" style="flex: 1.2;"> <label>Reps</label> <input type="number" class="reps" min="1" placeholder="10" style="padding: 0.4rem;"> </div> <div class="form-group" style="flex: 1.2;"> <label>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; min-width: 100px;"> <label style="display: inline-flex; align-items: center; color: #bbb; font-size: 0.8rem; margin-bottom: 0; white-space: nowrap;"> <input type="checkbox" class="degressive-checkbox" style="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-basis: 30px; flex-grow: 0; align-self: center;">×</button> </div>`;
            container.appendChild(seriesDiv); const removeBtn = seriesDiv.querySelector('.remove-series'); removeBtn.addEventListener('click', () => seriesDiv.remove());
        }

        function navigateExerciseForm(direction) {
            // S'assurer que la référence est à jour avant de naviguer
            workoutExercisesForm = Array.from(exercisesContainer.querySelectorAll('.exercise'));
            const newIndex = currentExerciseIndex + direction;
            if (newIndex >= 0 && newIndex < workoutExercisesForm.length) {
                currentExerciseIndex = newIndex;
                renderActiveExerciseForm();
            }
        }

        function renderActiveExerciseForm() {
            workoutExercisesForm = Array.from(exercisesContainer.querySelectorAll('.exercise'));
            workoutExercisesForm.forEach(ex => ex.classList.remove('active-exercise'));

            if (currentExerciseIndex >= 0 && currentExerciseIndex < workoutExercisesForm.length) {
                 const currentExDiv = workoutExercisesForm[currentExerciseIndex];
                 currentExDiv.classList.add('active-exercise');
                 // Logique style superset enlevée ici
            }
            updateExerciseNavButtons();
        }

         function updateExerciseNavButtons() {
             const totalExercises = workoutExercisesForm.length;
             if (totalExercises === 0) {
                 currentExerciseIndicator.textContent = "(Aucun exercice)";
                 prevExerciseBtn.disabled = true;
                 nextExerciseBtn.disabled = true;
             } else {
                 currentExerciseIndicator.textContent = `(${currentExerciseIndex + 1}/${totalExercises})`;
                 prevExerciseBtn.disabled = currentExerciseIndex === 0;
                 nextExerciseBtn.disabled = currentExerciseIndex === totalExercises - 1;
             }
         }

        function clearNewWorkoutForm() {
            if (!currentUser) return;
            document.getElementById('workout-name').value = ''; document.getElementById('workout-duration').value = '';
            setTodayDate(); exercisesContainer.innerHTML = ''; workoutExercisesForm = [];
            satisfactionRange.value = 75; satisfactionValue.textContent = '75%';
            currentWorkoutId = null; currentExerciseIndex = 0;
            addExercise(false); // Ajoute le premier vide
            renderActiveExerciseForm(); // Assure l'affichage correct
        }

        function saveWorkout() {
            if (!currentUser) return;

            // **CORRECTION : Rafraîchir la référence juste avant la validation**
            workoutExercisesForm = Array.from(exercisesContainer.querySelectorAll('.exercise'));

            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);

            if (!workoutName) { alert("Veuillez entrer un nom pour la séance."); return; }
            if (!workoutDate) { alert("Veuillez choisir une date pour la séance."); return; }
            if (workoutDuration <= 0) { alert("Veuillez entrer une durée valide (en minutes)."); return; }

            // Utiliser la référence fraîchement mise à jour
            const exerciseElements = workoutExercisesForm;
            const exercises = [];
            if (exerciseElements.length === 0) { alert("Veuillez ajouter au moins un exercice à la séance."); return; }

            let validationError = null;
             exerciseElements.forEach((exerciseEl, index) => { // Ajout index pour debug éventuel
                if (validationError) return;

                const nameInput = exerciseEl.querySelector('.exercise-name');
                const exerciseName = nameInput ? nameInput.value.trim() : ''; // Vérifier si l'input existe
                const isUnilateral = exerciseEl.querySelector('.unilateral-checkbox').checked;
                // isSupersetStart enlevé

                // **Point crucial de la validation du nom**
                if (!exerciseName) {
                    // Donner un indice (numéro de l'exercice basé sur l'ordre actuel)
                    validationError = `Veuillez nommer l'exercice #${index + 1}.`;
                    // Essayer de mettre le focus sur le champ vide si possible
                    if(nameInput) nameInput.focus();
                    return;
                }

                const series = [];
                const seriesElements = exerciseEl.querySelectorAll('.series');
                if (seriesElements.length === 0) { validationError = `L'exercice "${exerciseName}" doit contenir au moins une série.`; return; }

                seriesElements.forEach(seriesEl => {
                     if (validationError) return;
                    const repsInput = seriesEl.querySelector('.reps'); const weightInput = seriesEl.querySelector('.weight');
                    const reps = parseInt(repsInput.value) || 0; const weight = parseFloat(weightInput.value) || 0;
                    const isDegressive = seriesEl.querySelector('.degressive-checkbox').checked;
                    if (reps <= 0) { validationError = `Reps invalides pour une série de "${exerciseName}".`; if(repsInput) repsInput.focus(); return; }
                    if (weight < 0) { validationError = `Charge invalide pour une série de "${exerciseName}".`; if(weightInput) weightInput.focus(); return; }
                    series.push({ reps, weight, isDegressive });
                });

                if (!validationError) {
                     // **Objet exercice SANS isSupersetStart**
                    exercises.push({ name: exerciseName, isUnilateral, series });
                }
            });

            if (validationError) { alert(validationError); return; }

            // --- Calcul Tonnage ---
            let totalTonnage = 0;
            exercises.forEach(exercise => {
                exercise.series.forEach(serie => {
                    const weightFactor = exercise.isUnilateral ? 2 : 1;
                    totalTonnage += serie.reps * serie.weight * weightFactor;
                });
            });

            // --- Création/MAJ Objet Workout ---
            const workout = {
                id: currentWorkoutId || `workout-${Date.now()}`, name: workoutName, date: workoutDate, duration: workoutDuration,
                exercises: exercises, // Utilise le tableau local `exercises`
                totalTonnage: totalTonnage, satisfaction: satisfaction
            };
            const existingIndex = workouts.findIndex(w => w.id === workout.id);
            if (existingIndex > -1) { workouts[existingIndex] = workout; } else { workouts.push(workout); }

            saveWorkouts();
            confetti({ particleCount: 150, spread: 90, origin: { y: 0.6 } }); // Confettis!
            showPage('home-page');
            renderWorkoutsList();
        }

        // --- Affichage et Stats ---
        function renderWorkoutsList() {
            if (!currentUser) return; workoutsList.innerHTML = ''; if (workouts.length === 0) { emptyWorkoutMessage.classList.remove('hidden'); updateStats(); return; } emptyWorkoutMessage.classList.add('hidden');
            const sortedWorkouts = [...workouts].sort((a, b) => new Date(b.date) - new Date(a.date));
            sortedWorkouts.forEach(workout => { const workoutDate = new Date(workout.date).toLocaleDateString('fr-FR', { year: 'numeric', month: 'short', day: 'numeric' }); const workoutDiv = document.createElement('div'); workoutDiv.className = 'card workout-card'; workoutDiv.setAttribute('data-workout-id', workout.id); workoutDiv.innerHTML = `<div class="workout-header"><h3 style="margin-bottom: 0.5rem;">${workout.name}</h3><div class="badge">${workoutDate}</div></div><div class="workout-details" style="font-size: 0.9rem; color: #ccc; margin-top: 0.5rem;"><span>${workout.duration} min</span> | <span>${workout.exercises.length} exo${workout.exercises.length > 1 ? 's' : ''}</span> | <span>${workout.totalTonnage.toFixed(1)} kg</span> | <span>${workout.satisfaction}%</span></div>`; workoutDiv.addEventListener('click', () => displayWorkoutDetails(workout.id)); workoutsList.appendChild(workoutDiv); });
            updateStats();
         }

        function displayWorkoutDetails(workoutId) {
            if (!currentUser) return; const workout = workouts.find(w => w.id === workoutId); if (!workout) { console.error("Séance non trouvée:", workoutId); showPage('home-page'); return; }
            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;
            const detailExercisesContainer = document.getElementById('detail-exercises-container'); detailExercisesContainer.innerHTML = '';

            // **Affichage détail SANS logique Superset**
            workout.exercises.forEach((exercise) => {
                const exerciseDiv = document.createElement('div');
                exerciseDiv.className = 'card detail-exercise-card'; // Juste la classe de base

                let seriesHtml = '';
                exercise.series.forEach((serie, sIndex) => {
                     const degressiveLabel = serie.isDegressive ? ' <span class="badge" style="font-size: 0.7rem; background-color: var(--accent-dark);">Dégr.</span>' : ''; const weightFactor = exercise.isUnilateral ? 2 : 1; const seriesTonnage = serie.reps * serie.weight * weightFactor;
                     seriesHtml += `<div class="exercise-summary"><div class="flex-between"><span>Série ${sIndex + 1}: ${serie.reps} reps × ${serie.weight} kg${degressiveLabel}</span><span style="color: #aaa;">(${seriesTonnage.toFixed(1)} kg)</span></div></div>`;
                 });

                const unilateralLabel = exercise.isUnilateral ? ' <span class="badge" style="font-size: 0.7rem;">Unilat.</span>' : '';
                 // Pas de supersetLabel ici

                exerciseDiv.innerHTML = `
                    <h3 style="font-size: 1.1rem; margin-bottom: 0.5rem;">${exercise.name}${unilateralLabel}</h3>
                    <div class="series-summary-container"> ${seriesHtml} </div>`;
                detailExercisesContainer.appendChild(exerciseDiv);
            });

            currentWorkoutId = workoutId;
            showPage('workout-details-page');
        }

        function deleteWorkout() {
             if (!currentUser || !currentWorkoutId) return; const workoutToDelete = workouts.find(w => w.id === currentWorkoutId); if (!workoutToDelete) return; const confirmDelete = confirm(`Supprimer séance "${workoutToDelete.name}" du ${new Date(workoutToDelete.date).toLocaleDateString('fr-FR')} ?`); if (!confirmDelete) return; workouts = workouts.filter(w => w.id !== currentWorkoutId); saveWorkouts(); currentWorkoutId = null; showPage('home-page'); renderWorkoutsList();
        }

        function updateStats() {
             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; } const totalTonnageAll = workouts.reduce((sum, workout) => sum + (workout.totalTonnage || 0), 0); const avgTonnage = totalTonnageAll / workoutCount; document.getElementById('stats-avg-tonnage').textContent = avgTonnage.toFixed(1); const totalSatisfaction = workouts.reduce((sum, workout) => sum + (workout.satisfaction || 0), 0); const avgSatisfaction = totalSatisfaction / workoutCount; document.getElementById('stats-avg-satisfaction').textContent = `${Math.round(avgSatisfaction)}%`;
        }

    </script>
</body>
</html>