File size: 34,633 Bytes
4946ffa
7bde1db
4946ffa
 
 
 
 
 
 
 
7bde1db
4946ffa
 
7bde1db
4946ffa
 
 
 
 
 
 
 
7bde1db
 
4946ffa
 
 
 
 
 
 
7bde1db
 
 
 
 
 
4946ffa
 
 
 
 
 
 
 
 
7bde1db
4946ffa
7bde1db
 
4946ffa
7bde1db
 
 
4946ffa
7bde1db
 
 
 
 
 
4946ffa
7bde1db
 
 
 
 
 
 
 
 
 
 
 
 
4946ffa
 
7bde1db
 
 
4946ffa
7bde1db
4946ffa
 
7bde1db
 
 
4946ffa
7bde1db
4946ffa
 
 
7bde1db
 
4946ffa
 
 
 
 
7bde1db
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4946ffa
7bde1db
 
4946ffa
 
 
 
 
7bde1db
 
4946ffa
 
 
7bde1db
 
 
 
 
 
 
 
 
 
 
 
 
4946ffa
7bde1db
 
4946ffa
7bde1db
 
 
4946ffa
 
7bde1db
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4946ffa
 
7bde1db
 
 
 
4946ffa
 
 
7bde1db
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4946ffa
7bde1db
 
 
 
 
 
4946ffa
 
7bde1db
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4946ffa
7bde1db
 
 
 
 
 
 
 
 
 
 
 
4946ffa
 
7bde1db
 
 
4946ffa
7bde1db
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4946ffa
7bde1db
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4946ffa
 
 
7bde1db
 
4946ffa
 
 
7bde1db
 
4946ffa
7bde1db
 
4946ffa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7bde1db
 
4946ffa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7bde1db
4946ffa
7bde1db
 
4946ffa
 
 
 
7bde1db
 
4946ffa
 
 
 
 
 
 
 
 
 
 
 
 
7bde1db
 
 
4946ffa
7bde1db
 
 
4946ffa
7bde1db
 
 
4946ffa
7bde1db
4946ffa
7bde1db
 
 
 
4946ffa
7bde1db
 
4946ffa
 
7bde1db
 
 
 
 
4946ffa
 
7bde1db
4946ffa
 
 
7bde1db
 
4946ffa
 
 
 
7bde1db
4946ffa
 
7bde1db
4946ffa
 
 
7bde1db
4946ffa
 
 
 
 
 
 
 
7bde1db
4946ffa
 
 
 
 
 
 
 
 
 
7bde1db
4946ffa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7bde1db
4946ffa
 
 
 
 
7bde1db
4946ffa
7bde1db
 
4946ffa
 
 
 
7bde1db
4946ffa
 
 
 
 
 
 
7bde1db
 
4946ffa
 
 
 
 
 
 
 
7bde1db
 
 
 
4946ffa
 
7bde1db
4946ffa
 
 
7bde1db
4946ffa
 
7bde1db
4946ffa
 
7bde1db
 
4946ffa
7bde1db
4946ffa
 
7bde1db
4946ffa
7bde1db
4946ffa
 
 
7bde1db
4946ffa
7bde1db
4946ffa
 
 
7bde1db
4946ffa
 
 
 
 
7bde1db
 
4946ffa
7bde1db
 
 
4946ffa
 
7bde1db
4946ffa
 
7bde1db
 
 
 
 
4946ffa
 
 
7bde1db
 
 
4946ffa
 
 
 
7bde1db
4946ffa
 
 
 
7bde1db
4946ffa
 
 
7bde1db
 
4946ffa
 
 
 
 
 
7bde1db
4946ffa
 
7bde1db
 
4946ffa
7bde1db
4946ffa
7bde1db
 
4946ffa
 
 
7bde1db
4946ffa
 
 
 
7bde1db
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4946ffa
7bde1db
4946ffa
7bde1db
 
4946ffa
7bde1db
4946ffa
7bde1db
4946ffa
 
 
7bde1db
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
<!DOCTYPE html>
<html lang="fr" class="">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Mariam AI</title>
  <!-- Tailwind CSS via CDN -->
  <script src="https://cdn.tailwindcss.com?plugins=forms,typography"></script>
  <!-- Font Awesome pour les icônes -->
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
  <!-- Google Fonts (Lexend pour le corps, JetBrains Mono pour le code) -->
  <link rel="preconnect" href="https://fonts.googleapis.com">
  <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
  <link href="https://fonts.googleapis.com/css2?family=Lexend:wght@300;400;500;600;700&family=JetBrains+Mono:wght@400;500&display=swap" rel="stylesheet">
  <!-- Favicon (Emoji amélioré) -->
  <link rel="icon" href="data:image/svg+xml,<svg xmlns=%22http://www.w3.org/2000/svg%22 viewBox=%220 0 100 100%22><text y=%22.9em%22 font-size=%2290%22>✨</text></svg>">
  <script>
    tailwind.config = {
      darkMode: 'class',
      theme: {
        extend: {
          fontFamily: {
            // Utilisation de la nouvelle police Lexend
            sans: ['Lexend', 'system-ui', 'sans-serif'],
            mono: ['"JetBrains Mono"', 'monospace']
          },
          colors: {
            primary: { 50: '#f0f9ff', 100: '#e0f2fe', 200: '#bae6fd', 300: '#7dd3fc', 400: '#38bdf8', 500: '#0ea5e9', 600: '#0284c7', 700: '#0369a1', 800: '#075985', 900: '#0c4a6e' },
            secondary: { 50: '#f8fafc', 100: '#f1f5f9', 200: '#e2e8f0', 300: '#cbd5e1', 400: '#94a3b8', 500: '#64748b', 600: '#475569', 700: '#334155', 800: '#1e293b', 900: '#0f172a' },
            accent: { 50: '#fdf4ff', 100: '#fae8ff', 200: '#f5d0fe', 300: '#f0abfc', 400: '#e879f9', 500: '#d946ef', 600: '#c026d3', 700: '#a21caf', 800: '#86198f', 900: '#701a75' }
          },
          // Ajout d'une animation pour le modal
          animation: { 'bounce-slow': 'bounce 2s infinite', 'pulse-slow': 'pulse 3s infinite', 'typing': 'typing 1.2s steps(3) infinite', 'dialog-show': 'dialog-show 0.2s ease-out forwards' },
          keyframes: { 
            typing: { '0%': { width: '0.15em' }, '50%': { width: '0.7em' }, '100%': { width: '0.15em' } },
            'dialog-show': { from: { opacity: 0, transform: 'scale(0.95)' }, to: { opacity: 1, transform: 'scale(1)' } }
          }
        }
      }
    }
  </script>
  <style>
    html {
      scroll-behavior: smooth;
    }
    body {
      font-family: 'Lexend', sans-serif;
      transition: background-color 0.3s ease, color 0.3s ease;
      background-color: #f8fafc;
      color: #1e293b;
    }
    .dark body {
      background-color: #020617; /* Fond plus sombre pour un meilleur contraste */
      color: #e2e8f0;
    }
    /* Nouvelle structure de layout pour le chat */
    .chat-container {
      display: flex;
      flex-direction: column;
      height: 100vh;
      width: 100%;
    }
    .chat-messages {
      flex-grow: 1;
      overflow-y: auto;
      padding-bottom: 1rem; /* Espace pour ne pas être collé au composer */
    }
    ::-webkit-scrollbar { width: 6px; height: 6px; }
    ::-webkit-scrollbar-track { background: transparent; }
    ::-webkit-scrollbar-thumb { background: #cbd5e1; border-radius: 6px; }
    .dark ::-webkit-scrollbar-thumb { background: #475569; }
    ::-webkit-scrollbar-thumb:hover { background: #94a3b8; }
    .dark ::-webkit-scrollbar-thumb:hover { background: #64748b; }

    /* Bulles de message améliorées */
    .message-bubble {
      max-width: 85%;
      border-radius: 1.25rem; /* Coins plus arrondis */
      padding: 0.75rem 1.125rem;
      line-height: 1.6;
      animation: message-fade-in 0.3s ease-out;
      box-shadow: 0 2px 4px rgba(0, 0, 0, 0.04);
      transition: transform 0.2s ease, box-shadow 0.2s ease;
    }
    .dark .message-bubble { box-shadow: 0 2px 5px rgba(0, 0, 0, 0.15); }
    .message-wrapper { display: flex; max-width: 100%; gap: 0.75rem; }
    .user-message-wrapper { justify-content: flex-end; }
    .user-message {
      background-color: #0ea5e9; /* Couleur primaire solide */
      color: white;
    }
    .assistant-message {
      background-color: #e2e8f0;
      color: #1e293b;
    }
    .dark .assistant-message {
      background-color: #1e293b;
      color: #e2e8f0;
    }
    /* Avatars pour les messages */
    .avatar {
      width: 2rem;
      height: 2rem;
      border-radius: 9999px;
      display: flex;
      align-items: center;
      justify-content: center;
      flex-shrink: 0;
      font-size: 1.125rem;
    }
    .assistant-avatar { background-color: #e0f2fe; color: #0284c7; }
    .dark .assistant-avatar { background-color: #0c4a6e; color: #7dd3fc; }
    .user-avatar { background-color: #dbeafe; color: #1d4ed8; }
    .dark .user-avatar { background-color: #1e3a8a; color: #93c5fd; }

    @keyframes message-fade-in {
      from { opacity: 0; transform: translateY(10px) scale(0.98); }
      to { opacity: 1; transform: translateY(0) scale(1); }
    }
    @keyframes pulse-fade {
      0%, 100% { opacity: 0.5; }
      50% { opacity: 1; }
    }
    .typing-indicator { display: inline-flex; align-items: center; }
    .typing-dot { width: 0.4rem; height: 0.4rem; border-radius: 50%; background-color: currentColor; opacity: 0.7; margin: 0 0.1rem; }
    .typing-dot:nth-child(1) { animation: pulse-fade 1.2s 0s infinite; }
    .typing-dot:nth-child(2) { animation: pulse-fade 1.2s 0.2s infinite; }
    .typing-dot:nth-child(3) { animation: pulse-fade 1.2s 0.4s infinite; }

    /* Tooltip amélioré */
    .tooltip { position: relative; }
    .tooltip .tooltip-text { visibility: hidden; width: max-content; background-color: #1e293b; color: #f8fafc; text-align: center; border-radius: 6px; padding: 0.375rem 0.625rem; position: absolute; z-index: 10; bottom: 125%; left: 50%; transform: translateX(-50%); opacity: 0; transition: opacity 0.3s, visibility 0.3s; font-size: 0.75rem; font-weight: 500; pointer-events: none; }
    .dark .tooltip .tooltip-text { background-color: #e2e8f0; color: #1e293b; }
    .tooltip:hover .tooltip-text { visibility: visible; opacity: 1; }

    /* Bouton de copie amélioré */
    .copy-btn { position: absolute; top: 0.5rem; right: 0.5rem; opacity: 0; transition: all 0.2s ease; z-index: 2; transform: scale(0.9); }
    .message-bubble:hover .copy-btn { opacity: 1; transform: scale(1); }
    
    /* Composer (zone de saisie) */
    .chat-composer {
      background-color: white;
      border-top: 1px solid #e2e8f0;
      transition: background-color 0.3s ease, border-color 0.3s ease;
    }
    .dark .chat-composer {
      background-color: #0f172a;
      border-top-color: #1e293b;
    }
    .chat-textarea {
      resize: none; min-height: 48px; max-height: 200px; line-height: 1.5;
      background-color: transparent; border: none;
    }
    .chat-textarea:focus { box-shadow: none; ring: 0; }
    
    /* Toggle Switch */
    .toggle-switch { position: relative; display: inline-block; width: 2.5rem; height: 1.25rem; }
    .toggle-switch input { opacity: 0; width: 0; height: 0; }
    .toggle-slider { position: absolute; cursor: pointer; top: 0; left: 0; right: 0; bottom: 0; background-color: #cbd5e1; transition: .4s; border-radius: 1.25rem; }
    .toggle-slider:before { position: absolute; content: ""; height: 0.875rem; width: 0.875rem; left: 0.25rem; bottom: 0.1875rem; background-color: white; transition: .4s; border-radius: 50%; }
    input:checked + .toggle-slider { background-color: #0ea5e9; }
    .dark .toggle-slider { background-color: #475569; }
    .dark input:checked + .toggle-slider { background-color: #38bdf8; }
    input:checked + .toggle-slider:before { transform: translateX(1.125rem); }

    /* Styles pour le code et les tableaux */
    pre { position: relative; background-color: #f1f5f9; border-radius: 0.5rem; margin: 1rem 0; padding: 1.25rem 1rem; overflow-x: auto; }
    .dark pre { background-color: #0f172a; }
    code { font-family: 'JetBrains Mono', monospace; font-size: 0.875rem; }
    .code-copy-btn { position: absolute; top: 0.5rem; right: 0.5rem; opacity: 0; transition: opacity 0.2s ease; }
    pre:hover .code-copy-btn { opacity: 0.7; }
    .table-wrapper { width: 100%; overflow-x: auto; margin: 1rem 0; border: 1px solid #e2e8f0; border-radius: 0.5rem; }
    .dark .table-wrapper { border-color: #334155; }
    .prose table { width: 100%; min-width: 100%; border-collapse: collapse; margin: 0; }
    .prose table th, .prose table td { border: 1px solid #e2e8f0; padding: 0.5rem 0.75rem; text-align: left; }
    .prose table th { border-bottom-width: 2px; }
    .dark .prose table th, .dark .prose table td { border-color: #334155; }
    .prose table thead { background-color: #f8fafc; font-weight: 600; }
    .dark .prose table thead { background-color: #1e293b; }

    /* Ajustements responsive */
    @media (max-width: 640px) {
      .message-bubble { padding: 0.625rem 1rem; }
      .chat-textarea { max-height: 120px; font-size: 1rem; min-height: 44px; }
      .prose table { font-size: 0.85rem; }
      .prose table th, .prose table td { padding: 0.375rem 0.5rem; }
    }
  </style>
</head>
<body class="antialiased">
  
  <div class="chat-container max-w-4xl mx-auto">
    <!-- Header amélioré -->
    <header class="bg-white/80 dark:bg-secondary-900/80 backdrop-blur-sm py-3 px-4 border-b border-secondary-200 dark:border-secondary-800 sticky top-0 z-20">
      <div class="flex justify-between items-center">
        <!-- Logo & Titre -->
        <div class="flex items-center space-x-3">
          <img src="https://mariam-241.vercel.app/static/image/logoboma.png" alt="Logo Mariam AI" class="h-8 sm:h-9 object-contain">
          <h1 class="text-xl font-bold text-secondary-800 dark:text-secondary-100">Mariam AI</h1>
        </div>
        <!-- Actions -->
        <div class="flex items-center space-x-1 sm:space-x-2">
          <button id="theme-toggle" class="p-2 w-10 h-10 rounded-full text-secondary-600 dark:text-secondary-300 hover:bg-secondary-100 dark:hover:bg-secondary-800 transition-colors duration-200 tooltip" aria-label="Changer de thème">
            <i class="fa-solid fa-moon dark:hidden"></i>
            <i class="fa-solid fa-sun hidden dark:inline"></i>
            <span class="tooltip-text">Thème</span>
          </button>
          <form action="/clear" method="POST" id="clear-form">
            <button type="submit" class="p-2 w-10 h-10 rounded-full text-red-500 hover:bg-red-500/10 transition-colors duration-200 focus:outline-none focus:ring-2 focus:ring-red-400 focus:ring-opacity-50 tooltip">
              <i class="fa-solid fa-trash-can"></i>
              <span class="tooltip-text">Effacer</span>
            </button>
          </form>
        </div>
      </div>
    </header>

    <!-- Main Content -->
    <main class="flex-grow flex flex-col">
      <!-- Conteneur des messages -->
      <section id="chat-messages" class="chat-messages flex flex-col space-y-5 p-4">
        <!-- Chargement de l'historique -->
        <div id="history-loading" class="text-center py-10">
          <div class="inline-flex items-center px-4 py-2 bg-primary-50 text-primary-700 rounded-lg dark:bg-primary-900/30 dark:text-primary-300">
            <svg class="animate-spin h-5 w-5 mr-3" viewBox="0 0 24 24">
              <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
              <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
            </svg>
            <span>Chargement de la conversation...</span>
          </div>
        </div>
        <!-- Indicateur de chargement pour les réponses -->
        <div id="loading-indicator" class="message-wrapper hidden">
            <div class="avatar assistant-avatar"></div>
            <div class="message-bubble assistant-message flex items-center">
              <div class="typing-indicator">
                <span class="typing-dot"></span>
                <span class="typing-dot"></span>
                <span class="typing-dot"></span>
              </div>
            </div>
        </div>
      </section>
    </main>

    <!-- Nouveau "Composer" unifié et sticky -->
    <div class="chat-composer sticky bottom-0 z-10 w-full">
      <div class="max-w-4xl mx-auto">
        <!-- Zone d'erreur -->
        <div id="error-message" class="bg-red-100 border-t-4 border-red-500 text-red-700 px-4 py-3 dark:bg-red-900/30 dark:text-red-300 dark:border-red-600 hidden" role="alert">
          <div class="flex items-center">
            <div class="flex-shrink-0"><i class="fa-solid fa-circle-exclamation mr-2"></i></div>
            <p class="text-sm font-medium" id="error-text">Le message d'erreur détaillé ira ici.</p>
            <button class="ml-auto -mr-1 p-1" id="dismiss-error"><i class="fa-solid fa-xmark"></i></button>
          </div>
        </div>
        <!-- Zone de prévisualisation -->
        <div id="preview-area" class="px-4 py-2 hidden">
          <div id="file-preview" class="hidden"></div>
        </div>
        <!-- Barre d'options -->
        <div class="flex items-center justify-between flex-wrap gap-y-2 px-4 py-2 text-sm text-gray-600 dark:text-gray-300">
           <div class="flex items-center space-x-4 flex-wrap gap-y-2">
             <label class="flex items-center cursor-pointer tooltip">
               <span class="mr-2 text-xs sm:text-sm font-medium"><i class="fa-solid fa-globe mr-1.5 opacity-70"></i><span class="hidden sm:inline">Web</span></span>
               <span class="toggle-switch"><input type="checkbox" id="web_search_toggle"><span class="toggle-slider"></span></span>
               <span class="tooltip-text">Recherche Web</span>
             </label>
             <label class="flex items-center cursor-pointer tooltip">
               <span class="mr-2 text-xs sm:text-sm font-medium text-accent-700 dark:text-accent-300">
                 <i class="fa-solid fa-brain mr-1.5"></i><span class="hidden sm:inline">Avancé</span><span id="advanced-cooldown-timer" class="text-xs ml-1 hidden"></span>
               </span>
               <span class="toggle-switch"><input type="checkbox" id="advanced_reasoning_toggle"><span class="toggle-slider"></span></span>
               <span class="tooltip-text">Raisonnement Avancé (1 fois/min)</span>
             </label>
           </div>
           <div class="flex items-center space-x-2">
             <label for="file_upload" class="cursor-pointer flex items-center text-primary-600 hover:text-primary-700 dark:text-primary-400 dark:hover:text-primary-300 tooltip">
               <i class="fa-solid fa-paperclip text-lg"></i>
               <input type="file" id="file_upload" name="file" class="hidden" accept=".txt,.pdf,.png,.jpg,.jpeg">
               <span class="tooltip-text">Joindre un fichier</span>
             </label>
             <div id="file-chip" class="chip hidden">
               <i class="fa-solid fa-file chip-icon"></i><span id="file-name" class="truncate max-w-[100px] sm:max-w-[120px]"></span><i id="clear-file" class="fa-solid fa-xmark chip-close"></i>
             </div>
           </div>
        </div>
        <!-- Formulaire de chat -->
        <form id="chat-form" class="p-3 sm:p-4">
          <div class="relative flex items-end bg-secondary-100 dark:bg-secondary-800 rounded-2xl">
            <textarea
              id="prompt"
              name="prompt"
              class="chat-textarea w-full pl-4 pr-12 focus:outline-none text-sm sm:text-base text-secondary-800 dark:text-secondary-100 placeholder-secondary-500 dark:placeholder-secondary-400"
              placeholder="Posez votre question à Mariam..."
              autocomplete="off"
              rows="1"></textarea>
            <button
              type="submit"
              id="send-button"
              class="absolute right-2 bottom-2 bg-primary-500 hover:bg-primary-600 disabled:bg-primary-300 disabled:cursor-not-allowed text-white rounded-full w-9 h-9 flex items-center justify-center transition-all duration-200 focus:outline-none focus:ring-2 focus:ring-primary-400"
              title="Envoyer">
              <i class="fa-solid fa-paper-plane text-sm"></i>
            </button>
          </div>
        </form>
      </div>
    </div>
  </div>

  <!-- Scripts -->
  <script>
    document.addEventListener('DOMContentLoaded', () => {
      // Sélection des éléments
      const chatForm = document.getElementById('chat-form');
      const promptInput = document.getElementById('prompt');
      const chatMessages = document.getElementById('chat-messages');
      const loadingIndicator = document.getElementById('loading-indicator');
      const historyLoadingIndicator = document.getElementById('history-loading');
      const errorMessageDiv = document.getElementById('error-message');
      const errorTextP = document.getElementById('error-text');
      const dismissErrorBtn = document.getElementById('dismiss-error');
      const webSearchToggle = document.getElementById('web_search_toggle');
      const fileUpload = document.getElementById('file_upload');
      const fileChip = document.getElementById('file-chip');
      const fileNameSpan = document.getElementById('file-name');
      const clearFileButton = document.getElementById('clear-file');
      const filePreview = document.getElementById('file-preview');
      const previewArea = document.getElementById('preview-area');
      const sendButton = document.getElementById('send-button');
      const clearForm = document.getElementById('clear-form');
      const advancedToggle = document.getElementById('advanced_reasoning_toggle');
      const advancedCooldownTimerSpan = document.getElementById('advanced-cooldown-timer');
      const themeToggleBtn = document.getElementById('theme-toggle');
      const API_CHAT_ENDPOINT = '/api/chat';
      const API_HISTORY_ENDPOINT = '/api/history';
      const CLEAR_ENDPOINT = '/clear';
      const COOLDOWN_DURATION = 60 * 1000;
      const MOBILE_BREAKPOINT = 640;
      let advancedToggleCooldownEndTime = 0;
      let isComposing = false;

      // Gestion du thème
      function initializeTheme() {
        if (localStorage.theme === 'dark' || (!('theme' in localStorage) && window.matchMedia('(prefers-color-scheme: dark)').matches)) {
          document.documentElement.classList.add('dark');
        } else {
          document.documentElement.classList.remove('dark');
        }
      }
      function toggleTheme() {
        document.documentElement.classList.toggle('dark');
        localStorage.theme = document.documentElement.classList.contains('dark') ? 'dark' : 'light';
      }
      themeToggleBtn.addEventListener('click', toggleTheme);
      initializeTheme();

      // Ajuster la hauteur du textarea
      function adjustTextareaHeight(textarea) {
        textarea.style.height = 'auto';
        const style = window.getComputedStyle(textarea);
        const maxHeight = parseInt(style.maxHeight, 10);
        const newHeight = Math.min(maxHeight || 200, textarea.scrollHeight);
        textarea.style.height = newHeight + 'px';
      }

      // Défilement vers le bas
      function scrollToBottom(smooth = true) {
        setTimeout(() => {
          chatMessages.scrollTo({ top: chatMessages.scrollHeight, behavior: smooth ? 'smooth' : 'auto' });
        }, 50);
      }

      // Affichage de l'indicateur de chargement
      function showLoading(show) {
        loadingIndicator.classList.toggle('hidden', !show);
        if (show) {
            chatMessages.appendChild(loadingIndicator);
            scrollToBottom();
        }
        sendButton.disabled = show;
        promptInput.disabled = show;
        fileUpload.disabled = show;
        clearFileButton.style.pointerEvents = show ? 'none' : 'auto';
        clearFileButton.style.opacity = show ? '0.5' : '0.7';
      }

      // Affichage des erreurs
      function displayError(message) {
        errorTextP.textContent = message || "Une erreur inconnue est survenue.";
        errorMessageDiv.classList.remove('hidden');
      }
      dismissErrorBtn.addEventListener('click', () => { errorMessageDiv.classList.add('hidden'); });

      // Ajout d'un message dans le chat
      function addMessageToChat(role, content, isHtml = false) {
        errorMessageDiv.classList.add('hidden');
        const messageWrapper = document.createElement('div');
        messageWrapper.className = `message-wrapper ${role === 'user' ? 'user-message-wrapper' : ''}`;
        
        let messageContentHtml = isHtml ? content : `<p class="whitespace-pre-wrap">${escapeHtml(content)}</p>`;

        const avatarClass = role === 'user' ? 'user-avatar' : 'assistant-avatar';
        const avatarIcon = role === 'user' ? '<i class="fa-regular fa-user"></i>' : '✨';
        const messageBubbleClass = role === 'user' ? 'user-message' : 'assistant-message';

        const bubbleHtml = `
            <div class="avatar ${avatarClass}">${avatarIcon}</div>
            <div class="message-bubble ${messageBubbleClass} relative">
                <div class="prose prose-sm sm:prose-base max-w-none dark:prose-invert">
                    ${messageContentHtml}
                </div>
                ${role === 'assistant' ? `
                <button class="copy-btn text-xs bg-white/70 dark:bg-gray-800/70 backdrop-blur-sm hover:bg-gray-200/70 dark:hover:bg-gray-700/70 py-1 px-2 rounded-full text-gray-600 dark:text-gray-300 flex items-center shadow">
                    <i class="fa-regular fa-copy mr-1.5"></i> Copier
                </button>` : ''}
            </div>
        `;
        
        messageWrapper.innerHTML = bubbleHtml;

        // Activation du bouton de copie (si assistant)
        const copyBtn = messageWrapper.querySelector('.copy-btn');
        if (copyBtn) {
          copyBtn.addEventListener('click', function() {
            const textToCopy = this.closest('.message-bubble').querySelector('.prose').innerText;
            navigator.clipboard.writeText(textToCopy).then(() => {
              const originalText = this.innerHTML;
              this.innerHTML = '<i class="fa-solid fa-check mr-1.5"></i> Copié';
              setTimeout(() => { this.innerHTML = originalText; }, 2000);
            }).catch(err => console.error('Copy failed:', err));
          });
        }
        
        // Activation de la copie pour les blocs de code
        const codeBlocks = messageWrapper.querySelectorAll('pre');
        codeBlocks.forEach(pre => {
          const code = pre.querySelector('code');
          if (!code || pre.querySelector('.code-copy-btn')) return;
          const copyButton = document.createElement('button');
          copyButton.innerHTML = '<i class="fa-regular fa-copy"></i>';
          copyButton.className = 'code-copy-btn p-1.5 bg-gray-200/50 dark:bg-gray-700/50 rounded-lg text-gray-600 dark:text-gray-300 hover:bg-gray-300/70 dark:hover:bg-gray-600/70 tooltip';
          copyButton.setAttribute('aria-label', 'Copier le code');
          const tooltipText = document.createElement('span');
          tooltipText.className = 'tooltip-text !text-xs';
          tooltipText.textContent = 'Copier';
          copyButton.appendChild(tooltipText);
          copyButton.addEventListener('click', () => {
            navigator.clipboard.writeText(code.innerText).then(() => {
              tooltipText.textContent = 'Copié!';
              copyButton.innerHTML = '<i class="fa-solid fa-check"></i>';
              setTimeout(() => {
                copyButton.innerHTML = '<i class="fa-regular fa-copy"></i>';
                copyButton.appendChild(tooltipText);
                tooltipText.textContent = 'Copier';
              }, 2000);
            });
          });
          pre.appendChild(copyButton);
        });

        chatMessages.insertBefore(messageWrapper, loadingIndicator);
        scrollToBottom();
      }
      function escapeHtml(unsafe) {
        return unsafe.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """).replace(/'/g, "'");
      }

      // Gestion du cooldown pour le raisonnement avancé
      function startAdvancedCooldownTimer() {
        advancedToggle.disabled = true;
        advancedToggleCooldownEndTime = Date.now() + COOLDOWN_DURATION;
        const intervalId = setInterval(() => {
          const now = Date.now();
          if (now >= advancedToggleCooldownEndTime) {
            clearInterval(intervalId);
            advancedCooldownTimerSpan.classList.add('hidden');
            advancedToggle.disabled = false;
            advancedToggleCooldownEndTime = 0;
          } else {
            const remainingSeconds = Math.ceil((advancedToggleCooldownEndTime - now) / 1000);
            advancedCooldownTimerSpan.textContent = `(${remainingSeconds}s)`;
            advancedCooldownTimerSpan.classList.remove('hidden');
          }
        }, 1000);
      }
      
      // Chargement de l'historique du chat
      async function loadChatHistory() {
        historyLoadingIndicator.style.display = 'flex';
        try {
          const response = await fetch(API_HISTORY_ENDPOINT);
          if (!response.ok) throw new Error(`Erreur serveur (${response.status})`);
          const data = await response.json();
          chatMessages.innerHTML = ''; // Clear everything including loading indicator template
          chatMessages.appendChild(loadingIndicator);
          if (data.success && Array.isArray(data.history)) {
            if (data.history.length === 0) {
              addMessageToChat('assistant', "Bonjour ! Je suis Mariam, votre assistant IA. Comment puis-je vous aider aujourd'hui ?", true);
            } else {
              data.history.forEach(message => addMessageToChat(message.role, message.text, message.role === 'assistant'));
            }
            scrollToBottom(false);
          } else {
            throw new Error(data.error || "Format de réponse invalide pour l'historique.");
          }
        } catch (error) {
          displayError(`Impossible de charger l'historique: ${error.message}`);
          if (chatMessages.querySelectorAll('.message-wrapper').length === 0) {
            addMessageToChat('assistant', "Bonjour ! Je suis Mariam. Je n'ai pas pu charger notre conversation précédente.", true);
          }
        } finally {
          historyLoadingIndicator.remove();
          promptInput.focus();
          adjustTextareaHeight(promptInput);
        }
      }

      // ... le reste du JS pour la gestion des fichiers, la soumission du formulaire, etc. reste très similaire
      // et fonctionnera avec la nouvelle structure. Je vais juste recopier la partie pertinente du script original
      // en m'assurant que les sélecteurs sont toujours corrects.

      // Gestion des fichiers
      function clearFileInput() {
        fileUpload.value = ''; fileChip.classList.add('hidden'); fileNameSpan.textContent = ''; fileNameSpan.title = ''; filePreview.innerHTML = ''; filePreview.classList.add('hidden'); previewArea.classList.add('hidden');
      }
      fileUpload.addEventListener('change', () => {
        if (fileUpload.files.length > 0) {
          const file = fileUpload.files[0]; const name = file.name; fileNameSpan.textContent = name; fileNameSpan.title = name; fileChip.classList.remove('hidden'); filePreview.innerHTML = '';
          if (file.type.startsWith('image/')) {
            const reader = new FileReader();
            reader.onload = (e) => { filePreview.innerHTML = `<div class="file-preview"><img src="${e.target.result}" alt="Prévisualisation: ${escapeHtml(name)}"></div>`; filePreview.classList.remove('hidden'); previewArea.classList.remove('hidden'); };
            reader.readAsDataURL(file);
          } else {
            filePreview.innerHTML = `<div class="flex items-center justify-center p-3"><div class="bg-gray-100 dark:bg-gray-800 p-3 rounded-lg text-center"><i class="fa-solid fa-file text-3xl text-gray-500 dark:text-gray-400 mb-2"></i><p class="text-xs text-gray-500 dark:text-gray-400">${name}</p></div></div>`;
            filePreview.classList.remove('hidden'); previewArea.classList.remove('hidden');
          }
        } else { clearFileInput(); }
      });
      clearFileButton.addEventListener('click', clearFileInput);
      
      // Événements pour le textarea
      promptInput.addEventListener('input', () => adjustTextareaHeight(promptInput));
      promptInput.addEventListener('keydown', (e) => {
        if (isComposing) return;
        const isMobile = window.innerWidth < MOBILE_BREAKPOINT;
        if (e.key === 'Enter' && !e.shiftKey && !isMobile) {
            e.preventDefault();
            chatForm.dispatchEvent(new Event('submit', { bubbles: true, cancelable: true }));
        }
      });
      promptInput.addEventListener('compositionstart', () => { isComposing = true; });
      promptInput.addEventListener('compositionend', () => { isComposing = false; setTimeout(() => adjustTextareaHeight(promptInput), 0); });
      adjustTextareaHeight(promptInput);

      // Soumission du formulaire
      chatForm.addEventListener('submit', async (e) => {
        e.preventDefault();
        const prompt = promptInput.value.trim(); const file = fileUpload.files[0];
        if (sendButton.disabled || (!prompt && !file)) return;
        errorMessageDiv.classList.add('hidden');
        if (advancedToggle.checked && advancedToggleCooldownEndTime > 0 && Date.now() < advancedToggleCooldownEndTime) {
          const remaining = Math.ceil((advancedToggleCooldownEndTime - Date.now()) / 1000);
          displayError(`Le raisonnement avancé est disponible dans ${remaining}s.`); return;
        }
        let userMessageText = prompt;
        if (file && file.name) { userMessageText = prompt ? `${prompt}\n[Fichier: ${file.name}]` : `[Fichier joint: ${file.name}]`; }
        addMessageToChat('user', userMessageText);
        const formData = new FormData();
        formData.append('prompt', prompt); formData.append('web_search', webSearchToggle.checked); formData.append('advanced_reasoning', advancedToggle.checked);
        if (file) formData.append('file', file);
        promptInput.value = ''; adjustTextareaHeight(promptInput); clearFileInput();
        if (advancedToggle.checked) { startAdvancedCooldownTimer(); advancedToggle.checked = false; }
        webSearchToggle.checked = false; showLoading(true);
        try {
          const response = await fetch(API_CHAT_ENDPOINT, { method: 'POST', body: formData });
          const data = await response.json();
          if (!response.ok) throw new Error(data.error || `Erreur serveur: ${response.status}`);
          if (data.success && data.message) addMessageToChat('assistant', data.message, true);
          else throw new Error(data.error || "Réponse invalide du serveur.");
        } catch (error) {
          console.error("Chat Error:", error);
          addMessageToChat('assistant', `<p class="text-red-600 dark:text-red-400">Désolé, une erreur est survenue :<br>${escapeHtml(error.message)}</p>`, true);
        } finally {
          showLoading(false); promptInput.focus();
        }
      });

      // Effacement de la conversation
      clearForm.addEventListener('submit', (e) => {
        e.preventDefault();
        const confirmDialog = document.createElement('div');
        confirmDialog.className = 'fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4';
        confirmDialog.innerHTML = `<div class="bg-white dark:bg-gray-800 p-6 rounded-lg shadow-xl max-w-sm w-full animate-dialog-show"><h3 class="text-lg font-semibold mb-3">Confirmer l'effacement</h3><p class="text-sm text-gray-600 dark:text-gray-300 mb-5">Voulez-vous vraiment effacer toute la conversation ?</p><div class="flex justify-end space-x-3"><button id="cancel-clear" class="px-4 py-2 text-sm font-medium bg-gray-100 dark:bg-gray-700 rounded hover:bg-gray-200 dark:hover:bg-gray-600">Annuler</button><button id="confirm-clear" class="px-4 py-2 text-sm font-medium text-white bg-red-600 rounded hover:bg-red-700">Effacer</button></div></div>`;
        const closeModal = () => document.body.contains(confirmDialog) && document.body.removeChild(confirmDialog);
        confirmDialog.querySelector('#cancel-clear').addEventListener('click', closeModal);
        confirmDialog.querySelector('#confirm-clear').addEventListener('click', async () => {
          closeModal();
          const clearButton = e.target.querySelector('button[type="submit"]');
          clearButton.disabled = true;
          try {
            const response = await fetch(CLEAR_ENDPOINT, { method: 'POST', headers: { 'X-Requested-With': 'XMLHttpRequest' } });
            const data = await response.json();
            if (response.ok && data.success) {
              chatMessages.innerHTML = ''; chatMessages.appendChild(loadingIndicator);
              addMessageToChat('assistant', "Conversation effacée. Comment puis-je vous aider ?", true);
            } else {
              throw new Error(data.error || "Impossible d'effacer.");
            }
          } catch (error) { displayError(`Erreur: ${error.message}`);
          } finally { clearButton.disabled = false; }
        });
        document.body.appendChild(confirmDialog);
      });
      
      // Initialisation
      loadChatHistory();

      // Observer pour les tableaux Markdown
      new MutationObserver(mutations => {
        mutations.forEach(mutation => {
          if (mutation.addedNodes.length) {
            mutation.addedNodes.forEach(node => {
              if (node.nodeType === 1) {
                const tables = node.matches('.prose table') ? [node] : node.querySelectorAll('.prose table');
                tables.forEach(table => {
                  if (!table.closest('.table-wrapper')) {
                    const wrapper = document.createElement('div');
                    wrapper.className = 'table-wrapper';
                    table.parentNode.insertBefore(wrapper, table);
                    wrapper.appendChild(table);
                  }
                });
              }
            });
          }
        });
      }).observe(chatMessages, { childList: true, subtree: true });

      // Gestion du thème système
      window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', e => {
        if (!localStorage.getItem('theme')) {
            document.documentElement.classList.toggle('dark', e.matches);
        }
      });
    });
  </script>
</body>
</html>