File size: 29,123 Bytes
ecb5f6f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
<!DOCTYPE html>
<html lang="fr">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Mariam Espagnol - Analyse de Documents</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <script src="https://unpkg.com/[email protected]/marked.min.js"></script>
    <!-- SweetAlert2 -->
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    <!-- PrismJS Core & Theme -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/prismjs/1.29.0/prism.min.js" integrity="sha512-7Z9J3l1+EYfeaPKcGXu3MS/7SluIYINAaicZN83z9/9XjUhIYU/YHwZxpTBIlXgy9XEOXRJW1QQkAcLpbzm7hA==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/prismjs/1.29.0/themes/prism-tomorrow.min.css" integrity="sha512-vswe+cgvic/XBoF1OcM/TeJ2FW0OofqAVdCZiEYkd6dwGXOyEVrd0XB9aLhtFOUUjLz90GzvnBCgXWLSntyo7w==" crossorigin="anonymous" referrerpolicy="no-referrer" />
    <!-- PrismJS Languages (Load components individually if needed, or use autoloader) -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/prismjs/1.29.0/components/prism-core.min.js" integrity="sha512-9khQRAUBYEJDCDVP2ywQ0LRUbnjL3ZfrPJorj7MF8+KEvn3chLJniiG9LUDXTQGshyrGXxGzvSgKyYad7is+7Q==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/prismjs/1.29.0/plugins/autoloader/prism-autoloader.min.js" integrity="sha512-GP4x8UWxWyh4BMbyJGOGneiTbUdnpcBtDbJcdM8XcSzaHjMTzOL/zENvu6QRGxzNssVSKHncmXbvH/SsqR2nLw==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

    <style>
        @import url('https://fonts.googleapis.com/css2?family=Playfair+Display:wght@400;700&family=Poppins:wght@300;400;500;600&display=swap');

        body {
            font-family: 'Poppins', sans-serif;
        }
        h1, h2, h3, h4, h5, h6 {
            font-family: 'Playfair Display', serif;
        }

        .fade-in { animation: fadeIn 0.5s ease-in; }
        .slide-up { animation: slideUp 0.5s ease-out; }
        @keyframes fadeIn { from { opacity: 0; } to { opacity: 1; } }
        @keyframes slideUp { from { transform: translateY(20px); opacity: 0; } to { transform: translateY(0); opacity: 1; } }

        .gradient-text {
            background: linear-gradient(45deg, #FF6B6B, #4ECDC4);
            -webkit-background-clip: text;
            background-clip: text;
            color: transparent;
        }
        .upload-zone {
            background: linear-gradient(145deg, #f9fafb, #f3f4f6);
            box-shadow: 5px 5px 15px #d1d9e6, -5px -5px 15px #ffffff;
            transition: all 0.3s ease;
        }
        .upload-zone.dragover {
            border-color: #4f46e5;
            background: #e0e7ff;
            transform: scale(1.02);
        }
        .waves { position: absolute; bottom: 0; left: 0; width: 100%; overflow: hidden; line-height: 0; transform: rotate(180deg); z-index: 0; }
        .waves svg { position: relative; display: block; width: calc(100% + 1.3px); height: 150px; }
        .waves .fill-indigo-50 { fill: #eef2ff; }

        /* Responsive Analysis Box & Prose */
        .prose { max-width: 100%; }
        .prose pre[class*="language-"] { /* Target only Prism <pre> blocks */
            background-color: #2d2d2d !important; /* Match Prism Tomorrow, use !important if needed */
            color: #ccc;
            padding: 1em;
            margin: 1.5em 0;
            overflow-x: auto;
            border-radius: 0.375rem;
            border: 1px solid #444; /* Subtle border */
        }
        .prose code[class*="language-"] { /* Target only Prism <code> blocks */
           font-family: Consolas, Monaco, 'Andale Mono', 'Ubuntu Mono', monospace; /* Monospace font */
           color: #ccc;
           background: none;
           text-shadow: none;
           font-size: 0.9em; /* Slightly smaller code font */
           direction: ltr;
           text-align: left;
           white-space: pre;
           word-spacing: normal;
           word-break: normal;
           line-height: 1.5;
           -moz-tab-size: 4;
           -o-tab-size: 4;
           tab-size: 4;
           -webkit-hyphens: none;
           -moz-hyphens: none;
           -ms-hyphens: none;
           hyphens: none;
        }
         /* Ensure inline code also gets styled if needed, but differently */
        .prose :not(pre) > code {
             background-color: #f3f4f6; /* Light gray background for inline code */
             color: #4b5563; /* Darker gray text */
             padding: 0.2em 0.4em;
             border-radius: 0.25rem;
             font-size: 0.9em;
        }
        .prose h1, .prose h2, .prose h3 { color: #1F2937; margin-top: 1.5em; margin-bottom: 0.8em; padding-bottom: 0.3em; border-bottom: 1px solid #e5e7eb; }
        .prose p { margin-bottom: 1.25em; line-height: 1.7; }
        .prose ul, .prose ol { margin-left: 1.5em; margin-bottom: 1.25em; }
        .prose li > p { margin-bottom: 0.5em; }
        /* Button disabled state */
        button:disabled {
            opacity: 0.5;
            cursor: not-allowed;
            background-color: #a5b4fc;
        }
        /* Fix potential Prism theme override from Tailwind */
        :not(pre) > code[class*="language-"], pre[class*="language-"] {
            background: #2d2d2d;
        }
    </style>
</head>
<body class="bg-gradient-to-br from-gray-50 to-gray-100 min-h-screen relative overflow-x-hidden">
    <div class="waves">
        <svg data-name="Layer 1" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1200 120" preserveAspectRatio="none">
            <path d="M321.39,56.44c58-10.79,114.16-30.13,172-41.86,82.39-16.72,168.19-17.73,250.45-.39C823.78,31,906.67,72,985.66,92.83c70.05,18.48,146.53,26.09,214.34,3V0H0V27.35A600.21,600.21,0,0,0,321.39,56.44Z" class="fill-indigo-50"></path>
        </svg>
    </div>

    <div class="max-w-4xl mx-auto px-4 py-12 relative z-10">
        <!-- Header -->
        <header class="text-center mb-12 fade-in">
            <h1 class="text-4xl md:text-5xl font-bold mb-3 font-['Playfair_Display'] gradient-text">
                Mariam Espagnol
            </h1>
            <p class="text-lg text-gray-600 font-light max-w-xl mx-auto">
                Analysez vos documents iconographiques ou textuels en espagnol
            </p>
        </header>

        <!-- Main Content -->
        <div class="bg-white rounded-2xl shadow-xl p-6 md:p-8 mb-8 slide-up">
            <!-- File Type Selection -->
            <div class="mb-6">
                <label class="block text-base font-medium text-gray-700 mb-3">1. Choisissez le type de document</label>
                <div class="flex flex-col sm:flex-row gap-4">
                    <label class="relative flex items-center group cursor-pointer p-3 border border-gray-200 rounded-lg hover:bg-indigo-50 transition-colors w-full">
                        <input type="radio" name="fileType" value="image" checked
                               class="peer sr-only file-type-radio">
                        <div class="w-5 h-5 mr-3 border-2 border-gray-300 rounded-full flex-shrink-0 peer-checked:border-indigo-500 peer-checked:bg-indigo-500 transition-all"></div>
                        <span class="text-sm text-gray-700 group-hover:text-indigo-600">Document iconographique (Image, Photo, Dessin...) avec méthodologie.</span>
                    </label>
                    <label class="relative flex items-center group cursor-pointer p-3 border border-gray-200 rounded-lg hover:bg-indigo-50 transition-colors w-full">
                        <input type="radio" name="fileType" value="text"
                               class="peer sr-only file-type-radio">
                        <div class="w-5 h-5 mr-3 border-2 border-gray-300 rounded-full flex-shrink-0 peer-checked:border-indigo-500 peer-checked:bg-indigo-500 transition-all"></div>
                        <span class="text-sm text-gray-700 group-hover:text-indigo-600">Document textuel (Texte, PDF lisible...) avec méthodologie.</span>
                    </label>
                </div>
            </div>

            <!-- Upload Zone -->
             <div class="mb-6">
                 <label class="block text-base font-medium text-gray-700 mb-3">2. Sélectionnez votre fichier</label>
                 <div id="upload-zone" class="upload-zone border-2 border-dashed border-gray-300 rounded-xl p-6 text-center cursor-pointer transition-all duration-300 relative overflow-hidden">
                    <input id="file-upload" name="file" type="file" class="sr-only" accept="image/*">
                    <div class="space-y-3">
                        <div class="w-16 h-16 mx-auto rounded-full bg-indigo-100 flex items-center justify-center border-4 border-white shadow-sm">
                            <svg class="w-8 h-8 text-indigo-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M7 16a4 4 0 01-.88-7.903A5 5 0 1115.9 6L16 6a5 5 0 011 9.9M15 13l-3-3m0 0l-3 3m3-3v12"/>
                            </svg>
                        </div>
                        <div class="text-sm text-gray-600">
                            <label for="file-upload" class="relative cursor-pointer rounded-md font-medium text-indigo-600 hover:text-indigo-500 focus-within:outline-none focus-within:ring-2 focus-within:ring-offset-2 focus-within:ring-indigo-500">
                                <span>Déposez votre fichier ici</span>
                            </label>
                            <span class="text-gray-500"> ou </span>
                            <label for="file-upload" class="cursor-pointer text-indigo-600 hover:text-indigo-500 font-medium">cliquez pour sélectionner</label>
                        </div>
                        <p class="text-xs text-gray-500" id="file-types-info">Images (PNG, JPG, GIF) ou Textes (TXT, PDF) - Max 16MB</p>
                    </div>
                 </div>
            </div>

            <!-- Preview -->
            <div id="preview" class="mt-6 hidden slide-up">
                <h3 class="text-base font-medium text-gray-800 mb-3">Aperçu</h3>
                <div class="preview-container border rounded-lg p-4 bg-gray-50 max-h-72 overflow-auto relative">
                    <img id="image-preview" class="max-w-full h-auto hidden rounded block mx-auto" alt="Aperçu Image">
                    <pre id="text-preview" class="text-sm text-gray-700 whitespace-pre-wrap hidden bg-white p-3 rounded shadow-inner"></pre>
                    <p id="file-info" class="text-xs text-gray-500 mt-2 text-center"></p>
                     <button id="remove-file-button" class="absolute top-2 right-2 bg-red-100 text-red-600 hover:bg-red-200 rounded-full p-1 text-xs hidden" title="Retirer le fichier">
                        <svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
                          <path stroke-linecap="round" stroke-linejoin="round" d="M6 18L18 6M6 6l12 12" />
                        </svg>
                    </button>
                </div>
            </div>

            <!-- Submit Button -->
            <div class="mt-6 text-center">
                <button id="submit-button"
                        disabled
                        class="bg-indigo-600 text-white font-medium py-2.5 px-6 rounded-lg shadow hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 transition duration-150 ease-in-out disabled:opacity-50 disabled:cursor-not-allowed disabled:bg-indigo-300">
                    <span id="submit-button-text">3. Lancer l'analyse</span>
                    <span id="submit-button-spinner" class="hidden">
                         <svg class="animate-spin inline-block -ml-1 mr-2 h-5 w-5 text-white" xmlns="http://www.w3.org/2000/svg" fill="none" 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>
                         Analyse en cours...
                    </span>
                </button>
            </div>

            <!-- Analysis Results -->
            <div id="results" class="mt-10 hidden slide-up">
                <h3 class="text-lg font-semibold text-gray-900 mb-4 border-b pb-2">Analyse détaillée</h3>
                <div class="bg-gray-50 rounded-lg p-4 md:p-6 shadow-inner overflow-x-auto border border-gray-200">
                    <!-- Applying prose styles here -->
                    <div id="analysis-content" class="prose prose-sm sm:prose-base max-w-none prose-indigo">
                        <p class="text-gray-500">L'analyse apparaîtra ici...</p>
                    </div>
                </div>
                 <div class="mt-4 text-right">
                    <button id="copy-analysis-button" class="text-sm bg-gray-200 hover:bg-gray-300 text-gray-700 font-medium py-1.5 px-3 rounded-md transition duration-150 ease-in-out">
                        Copier l'analyse
                    </button>
                </div>
            </div>
        </div> <!-- End main content block -->

        <footer class="text-center mt-12 text-gray-500 text-sm fade-in">
            <p>© 2025 Mariam Espagnol - Outil d'analyse</p>
        </footer>

    </div> <!-- End max-width container -->

    <script>
        document.addEventListener('DOMContentLoaded', function() {
            const uploadZone = document.getElementById('upload-zone');
            const fileInput = document.getElementById('file-upload');
            const preview = document.getElementById('preview');
            const imagePreview = document.getElementById('image-preview');
            const textPreview = document.getElementById('text-preview');
            const fileInfo = document.getElementById('file-info');
            const removeFileButton = document.getElementById('remove-file-button');
            const submitButton = document.getElementById('submit-button');
            const submitButtonText = document.getElementById('submit-button-text');
            const submitButtonSpinner = document.getElementById('submit-button-spinner');
            const results = document.getElementById('results');
            const analysisContent = document.getElementById('analysis-content');
            const copyAnalysisButton = document.getElementById('copy-analysis-button');
            const fileTypeRadios = document.querySelectorAll('.file-type-radio');
            const fileTypesInfo = document.getElementById('file-types-info');

            let selectedFile = null;

            // Configure marked with Prism check
            marked.setOptions({
                breaks: true,
                gfm: true,
                headerIds: false,
                mangle: false,
                highlight: function(code, lang) {
                    // ** Check if Prism and the language are loaded **
                    if (typeof Prism !== 'undefined' && Prism.languages[lang]) {
                        try {
                             return Prism.highlight(code, Prism.languages[lang], lang);
                        } catch (error) {
                            console.warn(`Prism highlighting failed for language ${lang}:`, error)
                            return code; // Return unhighlighted on error
                        }
                    }
                    // ** Fallback if Prism or language not available **
                    return code;
                }
            });

            // --- Helper Functions ---
            function showLoading(isLoading) {
                if (isLoading) {
                    submitButtonText.classList.add('hidden');
                    submitButtonSpinner.classList.remove('hidden');
                    submitButton.disabled = true;
                } else {
                    submitButtonText.classList.remove('hidden');
                    submitButtonSpinner.classList.add('hidden');
                    submitButton.disabled = (selectedFile === null);
                }
            }

            function resetUI() {
                selectedFile = null;
                fileInput.value = '';
                preview.classList.add('hidden');
                imagePreview.classList.add('hidden');
                textPreview.classList.add('hidden');
                imagePreview.src = '#';
                textPreview.textContent = '';
                fileInfo.textContent = '';
                removeFileButton.classList.add('hidden');
                results.classList.add('hidden');
                analysisContent.innerHTML = '<p class="text-gray-500">L\'analyse apparaîtra ici...</p>';
                submitButton.disabled = true;
                showLoading(false);
                updateAcceptAttribute();
            }

            function updateAcceptAttribute() {
                 const selectedType = document.querySelector('input[name="fileType"]:checked').value;
                 if (selectedType === 'image') {
                     fileInput.accept = "image/png, image/jpeg, image/gif, image/webp";
                     fileTypesInfo.textContent = "Images (PNG, JPG, GIF, WEBP) - Max 16MB";
                 } else {
                     fileInput.accept = "text/plain, application/pdf, .txt";
                     fileTypesInfo.textContent = "Textes (TXT, PDF lisible) - Max 16MB";
                 }
                 if (selectedFile) {
                    const currentFileTypeMatchesSelection =
                       (selectedType === 'image' && selectedFile.type.startsWith('image/')) ||
                       (selectedType === 'text' && (selectedFile.type === 'text/plain' || selectedFile.type === 'application/pdf' || selectedFile.name.endsWith('.txt')));

                    if(!currentFileTypeMatchesSelection) {
                        resetUI();
                         // Use SweetAlert for this message too
                        Swal.fire({
                            icon: 'warning',
                            title: 'Type de fichier changé',
                            text: 'Le type de document a été modifié. Veuillez resélectionner votre fichier.',
                        });
                    }
                 }
            }


            // --- Event Listeners ---
            fileTypeRadios.forEach(radio => {
                radio.addEventListener('change', updateAcceptAttribute);
            });
            uploadZone.addEventListener('click', () => fileInput.click());
            uploadZone.addEventListener('dragover', (e) => {
                e.preventDefault();
                uploadZone.classList.add('dragover');
            });
            uploadZone.addEventListener('dragleave', () => {
                uploadZone.classList.remove('dragover');
            });
            uploadZone.addEventListener('drop', (e) => {
                e.preventDefault();
                uploadZone.classList.remove('dragover');
                if (e.dataTransfer.files.length) {
                    handleFileSelection(e.dataTransfer.files[0]);
                }
            });
            fileInput.addEventListener('change', (e) => {
                if (e.target.files.length) {
                    handleFileSelection(e.target.files[0]);
                }
            });
            removeFileButton.addEventListener('click', resetUI);
            submitButton.addEventListener('click', handleSubmit);
            copyAnalysisButton.addEventListener('click', copyAnalysisToClipboard);


            // --- Core Logic Functions ---

            function handleFileSelection(file) {
                const fileType = document.querySelector('input[name="fileType"]:checked').value;
                const maxFileSize = 16 * 1024 * 1024;

                 if (file.size > maxFileSize) {
                    Swal.fire({ // Use SweetAlert
                        icon: 'error',
                        title: 'Fichier trop volumineux',
                        text: `La taille maximale autorisée est de 16 Mo. Votre fichier fait ${(file.size / 1024 / 1024).toFixed(1)} Mo.`,
                    });
                    resetUI();
                    return;
                }

                 const allowedImageTypes = ['image/png', 'image/jpeg', 'image/gif', 'image/webp'];
                 const allowedTextTypes = ['text/plain', 'application/pdf'];

                 if (fileType === 'image' && !allowedImageTypes.includes(file.type)) {
                    const isImageTypeByName = /\.(jpe?g|png|gif|webp)$/i.test(file.name);
                    if (!isImageTypeByName) {
                       Swal.fire({ // Use SweetAlert
                           icon: 'error',
                           title: 'Type de fichier invalide',
                           text: 'Veuillez sélectionner une image (PNG, JPG, GIF, WEBP).'
                       });
                       resetUI();
                       return;
                    }
                 } else if (fileType === 'text' && !allowedTextTypes.includes(file.type)) {
                    const isTextTypeByName = /\.txt$/i.test(file.name);
                     if (!isTextTypeByName && file.type !== 'application/pdf') {
                         Swal.fire({ // Use SweetAlert
                           icon: 'error',
                           title: 'Type de fichier invalide',
                           text: 'Veuillez sélectionner un fichier texte (TXT) ou PDF.'
                       });
                        resetUI();
                        return;
                    }
                 }

                // If validation passes:
                selectedFile = file;
                preview.classList.remove('hidden');
                preview.classList.add('fade-in');
                results.classList.add('hidden');
                analysisContent.innerHTML = '<p class="text-gray-500">L\'analyse apparaîtra ici...</p>';
                fileInfo.textContent = `${file.name} (${(file.size / 1024).toFixed(1)} Ko)`;
                removeFileButton.classList.remove('hidden');

                if (fileType === 'image') {
                    imagePreview.classList.remove('hidden');
                    textPreview.classList.add('hidden');
                    const reader = new FileReader();
                    reader.onload = (e) => imagePreview.src = e.target.result;
                    reader.readAsDataURL(file);
                } else {
                    imagePreview.classList.add('hidden');
                    textPreview.classList.remove('hidden');
                    if (file.type === 'application/pdf') {
                         textPreview.textContent = "Aperçu non disponible pour les fichiers PDF. Le contenu sera analysé.";
                    } else {
                         const reader = new FileReader();
                         reader.onload = (e) => textPreview.textContent = e.target.result;
                         reader.readAsText(file);
                    }
                }
                submitButton.disabled = false;
            }

            function handleSubmit() {
                if (!selectedFile) {
                     Swal.fire('Aucun fichier', 'Veuillez sélectionner un fichier avant de lancer l\'analyse.', 'warning');
                    return;
                }

                const fileType = document.querySelector('input[name="fileType"]:checked').value;
                const formData = new FormData();
                formData.append('file', selectedFile);
                formData.append('fileType', fileType);

                showLoading(true);
                results.classList.add('hidden');

                fetch('/upload', {
                    method: 'POST',
                    body: formData
                })
                .then(response => {
                    if (!response.ok) {
                         return response.json().then(errData => {
                            throw new Error(errData.error || `Erreur HTTP: ${response.status}`);
                         }).catch(() => {
                            throw new Error(`Erreur HTTP: ${response.status} ${response.statusText}`);
                         });
                    }
                    return response.json();
                })
                .then(data => {
                    showLoading(false);
                    if (data.success && data.analysis) {
                        results.classList.remove('hidden');
                        results.classList.add('slide-up');
                        analysisContent.innerHTML = marked.parse(data.analysis);

                        // ** Check if Prism is loaded before highlighting **
                        if (typeof Prism !== 'undefined') {
                             // Use Prism's autoloader or highlightAllUnder
                             // Prism.highlightAllUnder(analysisContent); // Might work with autoloader
                             // Or manually trigger highlighting on specific elements if autoloader fails:
                              analysisContent.querySelectorAll('pre code').forEach((block) => {
                                Prism.highlightElement(block);
                              });
                        } else {
                            console.warn("Prism n'est pas chargé, impossible de colorer la syntaxe.");
                        }

                        results.scrollIntoView({ behavior: 'smooth', block: 'start' });
                    } else {
                        throw new Error(data.error || "L'analyse n'a pas pu être générée.");
                    }
                })
                .catch(error => {
                    showLoading(false);
                    // Use SweetAlert for error display
                     Swal.fire({
                        icon: 'error',
                        title: 'Erreur lors de l\'analyse',
                        text: error.message || 'Une erreur inconnue est survenue.',
                    });
                    // Optionally log detailed error
                    console.error('Error during analysis:', error);
                    submitButton.disabled = false; // Re-enable on error
                });
            }

              function copyAnalysisToClipboard() {
                const analysisHtml = analysisContent.innerHTML;
                if (!analysisHtml || analysisHtml.includes('L\'analyse apparaîtra ici...')) {
                    Swal.fire('Rien à copier', 'Aucune analyse n\'a été générée pour le moment.', 'info');
                    return;
                }

                const tempDiv = document.createElement('div');
                tempDiv.innerHTML = analysisHtml;
                let textToCopy = tempDiv.textContent || tempDiv.innerText || "";

                 // Basic conversion for better text format
                 textToCopy = analysisHtml
                    .replace(/<br\s*\/?>/gi, '\n')
                    .replace(/<\/p>/gi, '\n')
                    .replace(/<\/li>/gi, '\n')
                    .replace(/<\/(h[1-6])>/gi, '\n\n')
                    .replace(/<pre.*?><code.*?>([\s\S]*?)<\/code><\/pre>/gi, '\n```\n$1\n```\n') // Attempt to format code blocks
                    .replace(/<[^>]+>/g, '') // Remove remaining tags
                    .replace(/</g, '<').replace(/>/g, '>').replace(/&/g, '&') // Decode entities
                    .trim();

                navigator.clipboard.writeText(textToCopy)
                    .then(() => {
                         // Use SweetAlert for success
                         Swal.fire({
                            icon: 'success',
                            title: 'Copié !',
                            text: 'L\'analyse a été copiée dans le presse-papiers.',
                            timer: 1500, // Auto-close after 1.5 seconds
                            showConfirmButton: false // Hide the confirmation button
                        });
                    })
                    .catch(err => {
                        console.error('Erreur de copie: ', err);
                         // Use SweetAlert for error
                         Swal.fire({
                            icon: 'error',
                            title: 'Erreur de copie',
                            text: 'Impossible de copier l\'analyse automatiquement. Vous pouvez essayer de la sélectionner manuellement.',
                        });
                    });
            }


            // --- Initial Setup ---
            updateAcceptAttribute();
            resetUI();

        }); // End DOMContentLoaded
    </script>
</body>
</html>