File size: 27,349 Bytes
ec9a9bd
5ca4462
 
a27075d
 
3a1bb56
a27075d
 
3a1bb56
a27075d
 
3a1bb56
 
 
 
 
 
a27075d
1bfe49c
 
a27075d
 
1bfe49c
a27075d
1bfe49c
 
a27075d
 
1bfe49c
 
a27075d
1bfe49c
 
a27075d
 
 
3a1bb56
a27075d
 
 
3a1bb56
 
 
 
 
 
a27075d
3a1bb56
a27075d
 
d1f8aa4
3a1bb56
 
a27075d
3a1bb56
 
 
 
 
 
 
a27075d
 
3a1bb56
 
 
 
 
 
 
 
a27075d
3a1bb56
 
 
 
a27075d
3a1bb56
a27075d
3a1bb56
a27075d
3a1bb56
 
 
 
 
 
 
 
 
 
 
a27075d
 
3a1bb56
a27075d
3a1bb56
 
 
 
 
a27075d
 
3a1bb56
a27075d
3a1bb56
 
 
 
 
a27075d
 
3a1bb56
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a27075d
 
3a1bb56
 
 
 
 
a27075d
 
 
 
 
 
 
3a1bb56
 
a27075d
 
 
 
 
 
 
 
 
 
 
 
3a1bb56
a27075d
3a1bb56
a27075d
 
 
 
 
 
 
 
 
3a1bb56
a27075d
3a1bb56
a27075d
 
 
3a1bb56
a27075d
 
 
 
3a1bb56
 
 
a27075d
3a1bb56
a27075d
 
 
 
 
3a1bb56
 
a27075d
3a1bb56
 
a27075d
3a1bb56
 
 
a27075d
3a1bb56
 
 
a27075d
 
 
 
 
 
 
3a1bb56
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d1f8aa4
 
3a1bb56
 
 
 
 
 
 
d1f8aa4
3a1bb56
 
d1f8aa4
3a1bb56
d1f8aa4
3a1bb56
 
 
 
 
 
 
 
 
 
 
d1f8aa4
3a1bb56
 
7c947e5
d1f8aa4
3a1bb56
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7c947e5
a27075d
3a1bb56
d1f8aa4
3a1bb56
 
 
 
 
7c947e5
 
3a1bb56
 
a27075d
3a1bb56
 
 
a27075d
 
3a1bb56
 
a27075d
 
 
 
3a1bb56
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a27075d
 
3a1bb56
 
 
 
 
a27075d
 
3a1bb56
a27075d
3a1bb56
 
 
 
 
 
 
 
 
 
a27075d
 
 
3a1bb56
a27075d
3a1bb56
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d1f8aa4
 
3a1bb56
 
 
 
 
 
 
a27075d
 
 
3a1bb56
 
 
d1f8aa4
3a1bb56
 
 
 
 
 
 
 
 
a27075d
 
3a1bb56
a27075d
 
3a1bb56
 
 
 
a27075d
3a1bb56
a27075d
 
3a1bb56
a27075d
3a1bb56
 
 
 
 
 
 
 
 
a27075d
3a1bb56
 
a27075d
3a1bb56
 
 
 
 
a27075d
3a1bb56
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a27075d
3a1bb56
 
 
 
 
1bfe49c
3a1bb56
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a27075d
3a1bb56
 
a27075d
3a1bb56
a27075d
3a1bb56
a27075d
3a1bb56
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a27075d
 
 
7c947e5
3a1bb56
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a27075d
 
 
3a1bb56
a27075d
 
3a1bb56
 
a27075d
3a1bb56
 
a27075d
3a1bb56
a27075d
3a1bb56
 
 
 
 
 
 
 
 
 
a27075d
3a1bb56
a27075d
 
 
3a1bb56
 
 
d1f8aa4
3a1bb56
 
a27075d
 
 
3a1bb56
 
 
 
 
 
 
 
 
 
 
 
 
a27075d
3a1bb56
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a27075d
 
 
3a1bb56
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a27075d
 
 
5ca4462
abf0cb6
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
<!DOCTYPE html>
<html lang="fr">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Mariam M-1 | Solution Mathématique</title>
  <!-- Tailwind CSS -->
  <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/tailwind.min.css" rel="stylesheet">

  <!-- SweetAlert2 -->
  <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

  <!-- Highlight.js pour la coloration syntaxique -->
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.7.0/styles/github.min.css">
  <script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.7.0/highlight.min.js"></script>

  <!-- Configuration de MathJax -->
  <script>
    window.MathJax = {
      tex: {
        inlineMath: [['$', '$']],
        displayMath: [['$$', '$$']],
        processEscapes: true,
        packages: {'[+]': ['autoload', 'ams']}
      },
      options: {
        enableMenu: false,
        messageStyle: 'none'
      },
      startup: {
        pageReady: () => { window.mathJaxReady = true; }
      }
    };
  </script>
  <script src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js" id="MathJax-script" async></script>
  <script src="https://cdn.jsdelivr.net/npm/[email protected]/lib/marked.umd.min.js"></script>

  <style>
    @import url('https://fonts.googleapis.com/css2?family=Space+Grotesk:wght@400;700&display=swap');
    body { font-family: 'Space Grotesk', sans-serif; }

    .uploadArea {
      background: #f3f4f6;
      border: 2px dashed #d1d5db;
      transition: border-color 0.2s ease;
    }
    .uploadArea:hover { border-color: #3b82f6; }

    .blue-button { background: #3b82f6; transition: background-color 0.2s ease; }
    .blue-button:hover { background: #2563eb; }
    .blue-button:disabled { background: #9ca3af; cursor: not-allowed; }


    .loader {
      width: 48px;
      height: 48px;
      border: 3px solid #3b82f6;
      border-bottom-color: transparent;
      border-radius: 50%;
      display: inline-block;
      animation: rotation 1s linear infinite;
    }
    @keyframes rotation { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } }

    .thought-box {
      transition: max-height 0.3s ease-out;
      max-height: 0;
      overflow: hidden;
    }
    .thought-box.open { max-height: 500px; }

    #thoughtsContent, #answerContent {
      max-height: 500px;
      overflow-y: auto;
      scroll-behavior: smooth;
      white-space: pre-wrap;
    }

    .preview-image { max-width: 300px; max-height: 300px; object-fit: contain; }

    .timestamp { color: #3b82f6; font-size: 0.9em; margin-left: 8px; }

    table {
      border-collapse: collapse;
      width: 100%;
      margin-bottom: 1rem;
    }
    th, td {
      border: 1px solid #d1d5db;
      padding: 0.5rem;
      text-align: left;
    }
    th { background-color: #f3f4f6; font-weight: 600; }
    .table-responsive { overflow-x: auto; }

    #saveButton {
      background: #3b82f6;
      color: white;
      padding: 0.5rem 1rem;
      border-radius: 0.375rem;
      transition: background-color 0.2s ease;
    }
    #saveButton:hover { background: #2563eb; }

    #savedModal {
      display: none;
      position: fixed;
      inset: 0;
      background: rgba(0,0,0,0.5);
      z-index: 50;
    }
    #savedModal.active { display: block; }
    #savedModalContent {
      background: #fff;
      width: 100%;
      height: 100%;
      overflow-y: auto;
    }

    pre {
      background-color: #f8f8f8;
      border: 1px solid #e2e8f0;
      border-radius: 0.375rem;
      padding: 1rem;
      margin: 1rem 0;
      overflow-x: auto;
      font-family: 'Consolas', 'Monaco', 'Courier New', monospace;
    }

    code {
      font-family: 'Consolas', 'Monaco', 'Courier New', monospace;
    }

    .code-execution-result {
      background-color: #f0fff4;
      border-left: 4px solid #48bb78;
      padding: 1rem;
      margin: 1rem 0;
      font-family: 'Consolas', 'Monaco', 'Courier New', monospace;
      white-space: pre-wrap;
    }

    .content-text {}
    .content-code { padding: 0; }
    .content-result {
      background-color: #f0fff4;
      border-left: 4px solid #48bb78;
      padding: 1rem;
      margin: 0.5rem 0;
    }
    .content-image { margin: 1rem 0; text-align: center; }
    .content-image img { max-width: 100%; }

  </style>
</head>
<body class="p-4">
  <div class="max-w-4xl mx-auto">
    <header class="p-6 text-center mb-8">
      <h1 class="text-4xl font-bold text-blue-600">Mariam M-1(avec calculatrice)</h1>
      <p class="text-gray-600">Solution Mathématique/Physique/Chimie Intelligente, avec intégration d'une calculatrice.</p>
      <div class="mt-4 flex justify-end">
        <button id="openSaved" class="blue-button px-4 py-2 text-white rounded">Sauvegardes</button>
      </div>
    </header>

    <main id="mainContent">
      <form id="problemForm" class="space-y-6" novalidate>
        <div class="uploadArea p-8 text-center relative" aria-label="Zone de dépôt d'image">
          <input type="file" id="imageInput" name="image" accept="image/*" class="absolute inset-0 w-full h-full opacity-0 cursor-pointer" aria-label="Choisir une image">
          <div class="space-y-3">
            <div class="w-16 h-16 mx-auto border-2 border-blue-400 rounded-full flex items-center justify-center">
              <svg class="w-8 h-8 text-blue-400" fill="none" stroke="currentColor" viewBox="0 0 24 24" aria-hidden="true">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                  d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z" />
              </svg>
            </div>
            <p class="text-gray-700 font-medium">Déposez votre image ici</p>
            <p class="text-gray-500 text-sm">ou cliquez pour sélectionner</p>
          </div>
        </div>
        <div id="imagePreview" class="hidden text-center">
          <img id="previewImage" class="preview-image mx-auto" alt="Prévisualisation de l'image">
        </div>
        <button type="submit" id="submitProblemButton" class="blue-button w-full py-3 text-white font-medium rounded-lg">
          Résoudre le problème
        </button>
      </form>

      <div id="loader" class="hidden mt-8 text-center">
        <span class="loader"></span>
        <p class="mt-4 text-gray-600">Analyse en cours...</p>
      </div>

      <section id="solution" class="hidden mt-8 space-y-6 relative">
        <div class="border-t pt-4">
          <button id="thoughtsToggle" type="button" class="w-full flex justify-between items-center p-2">
            <span class="font-medium text-gray-700">Processus de Réflexion</span>
            <span id="timestamp" class="timestamp"></span>
          </button>
          <div id="thoughtsBox" class="thought-box">
            <div id="thoughtsContent" class="p-4 text-gray-600"></div>
          </div>
        </div>
        <div class="border-t pt-6">
          <div class="flex justify-between items-center">
            <h3 class="text-xl font-bold text-gray-800 mb-4">Solution</h3>
            <button id="saveButton">Sauvegarder</button>
          </div>
          <div id="answerContent" class="text-gray-700 table-responsive"></div>
        </div>
      </section>
    </main>
  </div>

  <div id="savedModal">
    <div id="savedModalContent" class="p-6">
      <header class="flex justify-between items-center border-b pb-4">
        <h2 class="text-2xl font-bold">Sauvegardes</h2>
        <button id="closeSaved" class="text-3xl text-gray-600">×</button>
      </header>
      <div id="savedListContainer" class="mt-4">
        <ul id="savedList" class="space-y-4">
        </ul>
      </div>
      <div class="mt-6">
        <button id="newExercise" class="blue-button w-full py-3 text-white font-medium rounded-lg">
          Résoudre un nouvel exercice
        </button>
      </div>
    </div>
  </div>

  <script>
    document.addEventListener('DOMContentLoaded', () => {
      const form = document.getElementById('problemForm');
      const imageInput = document.getElementById('imageInput');
      const loader = document.getElementById('loader');
      const solutionSection = document.getElementById('solution');
      const thoughtsContent = document.getElementById('thoughtsContent');
      const answerContent = document.getElementById('answerContent');
      const thoughtsToggle = document.getElementById('thoughtsToggle');
      const thoughtsBox = document.getElementById('thoughtsBox');
      const imagePreview = document.getElementById('imagePreview');
      const previewImage = document.getElementById('previewImage');
      const timestamp = document.getElementById('timestamp');
      const saveButton = document.getElementById('saveButton');
      const openSaved = document.getElementById('openSaved');
      const closeSaved = document.getElementById('closeSaved');
      const savedModal = document.getElementById('savedModal');
      const savedList = document.getElementById('savedList');
      const newExercise = document.getElementById('newExercise');
      const mainContent = document.getElementById('mainContent');
      const submitButton = document.getElementById('submitProblemButton'); // Récupérer le bouton de soumission

      let startTime = null;
      let timerInterval = null;
      let thoughtsBuffer = '';
      let answerBuffer = '';
      let currentMode = null;
      let updateTimeout = null;

      // Constantes pour la gestion du délai de soumission
      const SUBMISSION_COOLDOWN_MS = 3 * 60 * 1000; // 3 minutes
      const LAST_SUBMISSION_TIMESTAMP_KEY = 'mariamM1LastSubmissionTimestamp';
      let cooldownInterval = null;
      const ORIGINAL_SUBMIT_BUTTON_TEXT = 'Résoudre le problème';

      // Fonction pour activer le bouton de soumission
      const enableSubmitButton = () => {
        clearInterval(cooldownInterval);
        submitButton.disabled = false;
        submitButton.textContent = ORIGINAL_SUBMIT_BUTTON_TEXT;
      };

      // Fonction pour désactiver le bouton de soumission et afficher le compte à rebours
      const disableSubmitButton = (remainingTimeMs) => {
        if (remainingTimeMs <= 0) {
          enableSubmitButton();
          localStorage.removeItem(LAST_SUBMISSION_TIMESTAMP_KEY); // Nettoyer si le temps est écoulé
          return;
        }

        submitButton.disabled = true;
        clearInterval(cooldownInterval); // S'assurer qu'il n'y a pas d'intervalle précédent

        let timeLeft = Math.ceil(remainingTimeMs / 1000); // en secondes

        const updateButtonText = () => {
          if (timeLeft <= 0) {
            enableSubmitButton();
            localStorage.removeItem(LAST_SUBMISSION_TIMESTAMP_KEY); // Cooldown terminé
            return;
          }
          const minutes = Math.floor(timeLeft / 60);
          const seconds = timeLeft % 60;
          submitButton.textContent = `Attendre ${minutes}m ${seconds < 10 ? '0' : ''}${seconds}s`;
          timeLeft--;
        };

        updateButtonText(); // Appel initial
        cooldownInterval = setInterval(updateButtonText, 1000);
      };

      // Initialiser l'état du cooldown au chargement de la page
      const initializeCooldownState = () => {
        const lastSubmissionTime = parseInt(localStorage.getItem(LAST_SUBMISSION_TIMESTAMP_KEY), 10);
        if (lastSubmissionTime) {
          const now = Date.now();
          const timePassed = now - lastSubmissionTime;
          if (timePassed < SUBMISSION_COOLDOWN_MS) {
            const remainingTime = SUBMISSION_COOLDOWN_MS - timePassed;
            disableSubmitButton(remainingTime);
          } else {
            enableSubmitButton();
            localStorage.removeItem(LAST_SUBMISSION_TIMESTAMP_KEY); // Cooldown expiré
          }
        } else {
          enableSubmitButton();
        }
      };

      initializeCooldownState(); // Appeler à l'initialisation


      const updateTimestamp = () => {
        if (startTime) {
          const seconds = Math.floor((Date.now() - startTime) / 1000);
          timestamp.textContent = `${seconds}s`;
        }
      };
      const startTimer = () => { startTime = Date.now(); timerInterval = setInterval(updateTimestamp, 1000); updateTimestamp(); };
      const stopTimer = () => { clearInterval(timerInterval); startTime = null; /* Ne pas réinitialiser le timestamp ici si on veut le garder */};


      const handleFileSelect = file => {
        if (!file) return;
        const reader = new FileReader();
        reader.onload = e => {
          previewImage.src = e.target.result;
          imagePreview.classList.remove('hidden');
        };
        reader.readAsDataURL(file);
      };

      thoughtsToggle.addEventListener('click', () => { thoughtsBox.classList.toggle('open'); });
      imageInput.addEventListener('change', e => handleFileSelect(e.target.files[0]));

      const dropZone = document.querySelector('.uploadArea');
      dropZone.addEventListener('dragover', e => { e.preventDefault(); dropZone.classList.add('border-blue-400'); });
      dropZone.addEventListener('dragleave', e => { e.preventDefault(); dropZone.classList.remove('border-blue-400'); });
      dropZone.addEventListener('drop', e => { e.preventDefault(); dropZone.classList.remove('border-blue-400'); handleFileSelect(e.dataTransfer.files[0]); });

      const applyHighlighting = () => {
        document.querySelectorAll('pre code').forEach((block) => {
          hljs.highlightElement(block); // Utiliser highlightElement pour plus de contrôle si nécessaire
        });
      };

      const typesetAnswerIfReady = async () => {
        if (window.mathJaxReady) {
          MathJax.startup.document.elements = [document.getElementById('answerContent'), document.getElementById('thoughtsContent')];
          await MathJax.typesetPromise();
          applyHighlighting();
          answerContent.scrollTop = answerContent.scrollHeight;
          thoughtsContent.scrollTop = thoughtsContent.scrollHeight;
        } else { setTimeout(typesetAnswerIfReady, 200); }
      };

      const updateDisplay = async () => {
        thoughtsContent.innerHTML = marked.parse(thoughtsBuffer);
        answerContent.innerHTML = marked.parse(answerBuffer);
        await typesetAnswerIfReady();
        updateTimeout = null;
      };

      const scheduleUpdate = () => { if (!updateTimeout) updateTimeout = setTimeout(updateDisplay, 200); };

      marked.setOptions({
        gfm: true,
        breaks: true,
        highlight: function(code, lang) {
          if (lang && hljs.getLanguage(lang)) {
            try {
              return hljs.highlight(code, { language: lang, ignoreIllegals: true }).value;
            } catch (error) { console.error("Highlight.js error:", error); }
          }
          return hljs.highlightAuto(code).value; // Fallback to auto-detection
        }
      });

      form.addEventListener('submit', async e => {
        e.preventDefault();

        const lastSubmissionTime = parseInt(localStorage.getItem(LAST_SUBMISSION_TIMESTAMP_KEY), 10);
        const currentTime = Date.now();

        if (lastSubmissionTime && (currentTime - lastSubmissionTime < SUBMISSION_COOLDOWN_MS)) {
            const timePassed = currentTime - lastSubmissionTime;
            const remainingTime = SUBMISSION_COOLDOWN_MS - timePassed;
            const minutes = Math.floor(remainingTime / (1000 * 60));
            const seconds = Math.floor((remainingTime % (1000 * 60)) / 1000);

            Swal.fire({
                icon: 'warning',
                title: 'Délai d\'attente',
                text: `Veuillez attendre encore ${minutes} minute(s) et ${seconds} seconde(s) avant de soumettre à nouveau.`,
            });
            return; // Empêcher la soumission
        }

        const file = imageInput.files[0];
        if (!file) {
          Swal.fire({
            icon: 'error',
            title: 'Image manquante',
            text: 'Veuillez sélectionner une image.'
          });
          return;
        }

        // Marquer le temps de cette soumission et démarrer le cooldown
        localStorage.setItem(LAST_SUBMISSION_TIMESTAMP_KEY, currentTime.toString());
        disableSubmitButton(SUBMISSION_COOLDOWN_MS);

        startTimer();
        loader.classList.remove('hidden');
        solutionSection.classList.add('hidden');
        thoughtsContent.innerHTML = '';
        answerContent.innerHTML = '';
        thoughtsBuffer = '';
        answerBuffer = '';
        currentMode = null;
        thoughtsBox.classList.add('open');

        const formData = new FormData();
        formData.append('image', file);

        try {
          const response = await fetch('/solve', { method: 'POST', body: formData });

          if (!response.body) {
              throw new Error('Response body is not available (e.g., not a streaming response)');
          }

          const reader = response.body.getReader();
          const decoder = new TextDecoder();
          let streamBuffer = ''; // Renommé pour éviter confusion avec thoughtsBuffer/answerBuffer

          const processChunk = async chunk => {
            streamBuffer += decoder.decode(chunk, { stream: true });
            const lines = streamBuffer.split('\n\n');
            streamBuffer = lines.pop();

            for (const line of lines) {
              if (!line.startsWith('data:')) {
                  console.warn('Skipping non-data line:', line);
                  continue;
              }
              try {
                  const data = JSON.parse(line.slice(5));

                  if (data.mode) {
                    currentMode = data.mode;
                    loader.classList.add('hidden');
                    solutionSection.classList.remove('hidden');
                  }

                  if (data.content !== undefined) {
                    if (currentMode === 'thinking') {
                      thoughtsBuffer += data.content;
                    } else if (currentMode === 'answering') {
                      switch(data.type) {
                        case 'code':
                          answerBuffer += "\n```" + (data.language || '') + "\n" + data.content + "\n```\n";
                          break;
                        case 'result':
                           const formattedResult = data.content.split('\n').map(line => `> ${line}`).join('\n');
                           answerBuffer += "\n" + formattedResult + "\n";
                           break;
                        case 'image':
                          answerBuffer += `\n![Image générée](data:image/png;base64,${data.content})\n`;
                          break;
                        case 'text':
                        default:
                          answerBuffer += data.content;
                          break;
                      }
                    }
                  }
                  if (data.error) { answerBuffer += `\n**Erreur:** ${data.error}\n`; }
                } catch (e) {
                   console.error('Error parsing JSON data:', line.slice(5), e);
                   if (currentMode === 'thinking') { thoughtsBuffer += `\n[Erreur de Parsing des Données]`; }
                   else { answerBuffer += `\n[Erreur de Parsing des Données]`; }
                }
            }
            scheduleUpdate();
          };

          while (true) {
            const { done, value } = await reader.read();
            if (done) {
              if (streamBuffer.startsWith('data:')) { // Traiter le dernier morceau s'il existe
                try {
                  const data = JSON.parse(streamBuffer.slice(5));
                  if (data.content !== undefined) {
                    if (currentMode === 'thinking') { thoughtsBuffer += data.content; }
                    else if (currentMode === 'answering') { answerBuffer += data.content; } // Simplifié, ajuster si types nécessaires ici
                  }
                } catch(e) { console.error("Error parsing final buffer chunk:", e); }
              } else if (streamBuffer.trim() !== '') {
                console.warn("Final stream buffer part was not a data line:", streamBuffer);
              }
              scheduleUpdate();
              break;
            }
            await processChunk(value);
          }
          stopTimer();
        } catch (error) {
          console.error('Erreur de Fetch ou du Stream:', error);
          Swal.fire({
            icon: 'error',
            title: 'Erreur de connexion ou de traitement',
            text: `Une erreur est survenue: ${error.message}`
          });
          loader.classList.add('hidden');
          stopTimer();
          solutionSection.classList.remove('hidden');
          if(answerBuffer === '') {
             answerContent.innerHTML = `<div class="text-red-500">Une erreur est survenue: ${error.message}</div>`;
          } else {
             answerBuffer += `\n\n<div class="text-red-500 p-2 my-2 border border-red-500 rounded">Une erreur est survenue pendant le traitement: ${error.message}</div>`;
             scheduleUpdate();
          }
          // Le cooldown continue indépendamment de l'erreur de fetch.
        }
      });


      saveButton.addEventListener('click', () => {
        Swal.fire({
          title: 'Sauvegarder la solution',
          input: 'text',
          inputLabel: 'Nom de la sauvegarde',
          inputPlaceholder: 'Entrez un nom pour cette sauvegarde',
          showCancelButton: true,
          confirmButtonText: 'Sauvegarder',
          cancelButtonText: 'Annuler',
          inputValidator: (value) => {
            if (!value) { return 'Vous devez entrer un nom !' }
          }
        }).then((result) => {
          if (result.isConfirmed && result.value) {
            const saveName = result.value;
            const saveData = {
              answer: answerContent.innerHTML,
              thinking: thoughtsContent.innerHTML,
              date: new Date().toLocaleString()
            };
            let savedExercises = JSON.parse(localStorage.getItem('savedExercises') || '{}');
            savedExercises[saveName] = saveData;
            localStorage.setItem('savedExercises', JSON.stringify(savedExercises));
            Swal.fire('Sauvegardé !', 'Votre solution a été sauvegardée.', 'success');
          }
        });
      });

      const loadSavedList = () => {
        savedList.innerHTML = '';
        const savedExercises = JSON.parse(localStorage.getItem('savedExercises') || '{}');
        if (Object.keys(savedExercises).length === 0) {
          savedList.innerHTML = '<li class="text-gray-500 text-center py-8">Aucune sauvegarde disponible</li>';
          return;
        }
        const sortedEntries = Object.entries(savedExercises).sort(([,a], [,b]) => new Date(b.date) - new Date(a.date));
        for (const [name, data] of sortedEntries) {
          const li = document.createElement('li');
          li.className = 'border-b pb-2 mb-2'; // Ajout de mb-2 pour espacement
          li.innerHTML = `
            <div class="flex justify-between items-center">
              <button class="text-left text-blue-600 hover:underline focus:outline-none" data-save="${name}">
                <span class="font-semibold">${name}</span> <br> <span class="text-gray-500 text-xs">(${data.date})</span>
              </button>
              <button class="text-red-500 hover:text-red-700 p-1 focus:outline-none" data-delete="${name}" aria-label="Supprimer ${name}">
                <svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
                  <path stroke-linecap="round" stroke-linejoin="round" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
                </svg>
              </button>
            </div>
          `;
          savedList.appendChild(li);
        }
      };

      savedList.addEventListener('click', (e) => {
        const saveButtonTarget = e.target.closest('[data-save]');
        const deleteButtonTarget = e.target.closest('[data-delete]');

        if (saveButtonTarget) {
          const saveName = saveButtonTarget.dataset.save;
          const savedExercises = JSON.parse(localStorage.getItem('savedExercises') || '{}');
          const data = savedExercises[saveName];
          if (data) {
            form.classList.add('hidden');
            loader.classList.add('hidden');
            solutionSection.classList.remove('hidden');
            thoughtsContent.innerHTML = data.thinking;
            answerContent.innerHTML = data.answer;
            savedModal.classList.remove('active');
             if (window.mathJaxReady) {
                MathJax.startup.document.elements = [thoughtsContent, answerContent];
                MathJax.typesetPromise().then(applyHighlighting).catch(err => console.error("MathJax error on load:", err));
             } else { setTimeout(() => { if(window.mathJaxReady) MathJax.typesetPromise([thoughtsContent, answerContent]).then(applyHighlighting);}, 500); }
            thoughtsBox.classList.add('open');
            thoughtsBuffer = ''; answerBuffer = ''; stopTimer();
            timestamp.textContent = `Sauvegardé le: ${data.date}`;
          }
        } else if (deleteButtonTarget) {
          const deleteName = deleteButtonTarget.dataset.delete;
          Swal.fire({
            title: 'Êtes-vous sûr ?',
            text: "Cette sauvegarde sera définitivement supprimée.",
            icon: 'warning',
            showCancelButton: true,
            confirmButtonColor: '#d33',
            cancelButtonColor: '#3085d6',
            confirmButtonText: 'Oui, supprimer !',
            cancelButtonText: 'Annuler'
          }).then((result) => {
            if (result.isConfirmed) {
              const savedExercises = JSON.parse(localStorage.getItem('savedExercises') || '{}');
              delete savedExercises[deleteName];
              localStorage.setItem('savedExercises', JSON.stringify(savedExercises));
              Swal.fire('Supprimé !', 'La sauvegarde a été supprimée.', 'success');
              loadSavedList();
            }
          });
        }
      });

      openSaved.addEventListener('click', () => { loadSavedList(); savedModal.classList.add('active'); });
      closeSaved.addEventListener('click', () => { savedModal.classList.remove('active'); });

      newExercise.addEventListener('click', () => {
        form.reset();
        form.classList.remove('hidden');
        solutionSection.classList.add('hidden');
        imagePreview.classList.add('hidden');
        previewImage.src = '';
        thoughtsContent.innerHTML = '';
        answerContent.innerHTML = '';
        thoughtsBuffer = '';
        answerBuffer = '';
        currentMode = null;
        stopTimer();
        timestamp.textContent = '';
        thoughtsBox.classList.remove('open');
        savedModal.classList.remove('active');
        // Important: vérifier le cooldown pour le nouveau bouton d'exercice
        initializeCooldownState();
      });
    });
  </script>
</body>
</html>