Spaces:
Running

File size: 41,515 Bytes
d91d7db
 
 
 
 
5d295eb
d91d7db
 
5d295eb
 
d91d7db
5d295eb
 
d91d7db
5d295eb
 
 
d91d7db
5d295eb
 
d91d7db
5d295eb
 
 
d91d7db
5d295eb
 
 
d91d7db
5d295eb
 
d91d7db
5d295eb
 
d91d7db
5d295eb
 
d91d7db
 
 
 
5d295eb
 
 
 
d91d7db
 
097d82b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5d295eb
 
 
 
 
 
 
 
 
f43869d
 
 
5d295eb
 
 
 
 
 
 
 
 
 
 
 
 
 
d91d7db
 
 
 
5d295eb
 
d91d7db
 
5d295eb
 
 
d91d7db
 
5d295eb
d91d7db
5d295eb
 
 
 
 
 
 
 
d91d7db
5d295eb
 
d91d7db
 
 
5d295eb
 
 
 
 
d91d7db
5d295eb
9963ea3
f43869d
 
d91d7db
5d295eb
 
 
 
d91d7db
 
 
 
5d295eb
 
 
 
 
 
d91d7db
 
 
 
 
 
 
5d295eb
 
 
 
 
 
 
 
 
 
 
d91d7db
5d295eb
 
 
 
d91d7db
5d295eb
 
 
 
 
 
097d82b
 
 
 
 
 
 
d91d7db
 
5d295eb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
097d82b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5d295eb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d91d7db
 
 
5d295eb
 
 
 
 
 
 
d91d7db
5d295eb
 
 
 
 
 
 
 
 
 
 
 
 
 
d91d7db
5d295eb
 
 
 
d91d7db
5d295eb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d91d7db
5d295eb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d91d7db
5d295eb
d91d7db
5d295eb
 
 
 
 
 
 
 
 
 
 
d91d7db
5d295eb
 
 
 
 
d91d7db
 
5d295eb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d91d7db
 
 
5d295eb
 
 
 
 
 
 
 
 
 
 
 
 
 
d91d7db
 
5d295eb
 
 
 
 
 
 
 
 
 
 
 
 
d91d7db
5d295eb
 
 
 
 
 
50023e9
 
 
 
 
 
 
 
 
 
 
 
 
d91d7db
 
5d295eb
 
 
 
d91d7db
5d295eb
 
 
d91d7db
5d295eb
 
d91d7db
 
 
5d295eb
 
 
 
d91d7db
5d295eb
 
 
 
d91d7db
5d295eb
 
 
 
d91d7db
5d295eb
 
 
 
 
d91d7db
5d295eb
 
 
d91d7db
5d295eb
 
 
 
 
 
d91d7db
 
5d295eb
 
 
 
d91d7db
5d295eb
 
 
 
d91d7db
5d295eb
 
 
 
 
d91d7db
5d295eb
 
 
 
 
 
 
 
 
 
 
d91d7db
5d295eb
 
d91d7db
 
5d295eb
 
 
 
d91d7db
097d82b
5d295eb
097d82b
5d295eb
 
d91d7db
5d295eb
097d82b
 
 
 
 
 
 
 
 
 
5d295eb
097d82b
5d295eb
 
 
097d82b
d91d7db
5d295eb
 
 
 
 
 
097d82b
 
5d295eb
 
097d82b
 
5d295eb
d91d7db
5d295eb
 
 
 
 
 
097d82b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f9e2eaa
 
 
 
5d295eb
097d82b
d91d7db
097d82b
 
f9e2eaa
 
097d82b
9963ea3
097d82b
 
d91d7db
f9e2eaa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d91d7db
f9e2eaa
d91d7db
097d82b
f9e2eaa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d91d7db
f9e2eaa
097d82b
f9e2eaa
5d295eb
 
f9e2eaa
097d82b
 
 
 
 
 
 
 
 
5d295eb
 
f9e2eaa
5d295eb
 
097d82b
 
 
 
 
 
 
 
 
 
5d295eb
d91d7db
5d295eb
d91d7db
5d295eb
 
 
097d82b
5d295eb
097d82b
 
 
 
 
 
5d295eb
097d82b
 
 
f9e2eaa
 
 
d91d7db
097d82b
 
 
 
 
 
 
 
 
 
 
d91d7db
 
5d295eb
d91d7db
5d295eb
 
 
 
097d82b
5d295eb
097d82b
5d295eb
 
 
 
 
097d82b
 
 
 
 
 
 
 
 
 
 
 
 
 
5d295eb
097d82b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
438d7d6
 
 
 
 
097d82b
d91d7db
5d295eb
 
097d82b
5d295eb
 
097d82b
 
5d295eb
 
 
d91d7db
5d295eb
 
d91d7db
 
 
5d295eb
 
 
 
d91d7db
 
 
5d295eb
 
 
 
 
 
 
 
 
 
d91d7db
5d295eb
d91d7db
 
 
 
5d295eb
d91d7db
 
 
 
5d295eb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
097d82b
 
5d295eb
 
 
 
 
 
097d82b
 
 
 
5d295eb
 
 
 
 
 
 
d91d7db
5d295eb
 
d91d7db
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
<!DOCTYPE html>
<html lang="fr">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Classement Kip-Pic Suisse</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js"></script>
    <style>
        .drag-item {
            transition: transform 0.2s ease;
        }
        .drag-item.dragging {
            opacity: 0.5;
            transform: scale(1.05);
        }
        .tab-content {
            display: none;
        }
        .tab-content.active {
            display: block;
            animation: fadeIn 0.3s ease;
        }
        @keyframes fadeIn {
            from { opacity: 0; }
            to { opacity: 1; }
        }
        .trend-up {
            color: #10B981;
        }
        .trend-down {
            color: #EF4444;
        }
        .trend-stable {
            color: #6B7280;
        }
    </style>
</head>
<body class="bg-gray-50 min-h-screen">
    <div class="container mx-auto px-4 py-8 max-w-4xl">
        <header class="mb-8 text-center">
            <h1 class="text-3xl font-bold text-indigo-700">Classement Hebdomadaire Kip-Pic</h1>
            <p class="text-gray-600 mt-2">Analyse et suivi des blocs prioritaires</p>
        </header>

        <div class="bg-white rounded-lg shadow-md p-6 mb-8">
            <h2 class="text-xl font-semibold text-gray-800 mb-4">Sélection des blocs</h2>
            <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
                <div class="flex items-center">
                    <input type="checkbox" id="primo-info" class="mr-2" checked>
                    <label for="primo-info">Primo-info</label>
                </div>
                <div class="flex items-center">
                    <input type="checkbox" id="conseil" class="mr-2" checked>
                    <label for="conseil">Conseil</label>
                </div>
                <div class="flex items-center">
                    <input type="checkbox" id="langue" class="mr-2" checked>
                    <label for="langue">Langue</label>
                </div>
                <div class="flex items-center">
                    <input type="checkbox" id="petite-enfance" class="mr-2" checked>
                    <label for="petite-enfance">Petite-enfance</label>
                </div>
                <div class="flex items-center">
                    <input type="checkbox" id="employabilite" class="mr-2" checked>
                    <label for="employabilite">Employabilité</label>
                </div>
                <div class="flex items-center">
                    <input type="checkbox" id="vivre-ensemble" class="mr-2" checked>
                    <label for="vivre-ensemble">Vivre ensemble</label>
                </div>
            </div>
            <button id="apply-blocks-btn" class="mt-4 bg-indigo-600 text-white px-4 py-2 rounded-md text-sm font-medium hover:bg-indigo-700">
                Appliquer la sélection
            </button>
        </div>

        <div class="bg-white rounded-lg shadow-md overflow-hidden">
            <!-- Tabs Navigation -->
            <div class="flex border-b border-gray-200">
                <button class="tab-btn py-4 px-6 font-medium text-indigo-600 border-b-2 border-indigo-600" data-tab="ranking">
                    Classement
                </button>
                <button class="tab-btn py-4 px-6 font-medium text-gray-500 hover:text-indigo-500" data-tab="evolution">
                    Évolution
                </button>
                <button class="tab-btn py-4 px-6 font-medium text-gray-500 hover:text-indigo-500 text-sm" data-tab="history">
                    Historique
                </button>
            </div>

            <!-- Tab Contents -->
            <div class="p-6">
                <!-- Ranking Tab -->
                <div id="ranking" class="tab-content active">
                    <div class="mb-6 flex justify-between items-center">
                        <h2 class="text-xl font-semibold text-gray-800">Classement de la semaine</h2>
                        <div class="flex items-center space-x-2">
                            <select id="week-select" class="border rounded-md px-3 py-2 text-sm">
                                <!-- Options will be added by JS -->
                            </select>
                            <button id="new-week-btn" class="bg-indigo-100 text-indigo-700 px-3 py-2 rounded-md text-sm font-medium hover:bg-indigo-200">
                                Nouvelle semaine
                            </button>
                        </div>
                    </div>

                    <div id="blocks-container" class="space-y-3">
                        <!-- Blocks will be added by JS -->
                    </div>

                    <div class="mt-8 flex justify-end">
                        <button id="validate-btn" class="bg-indigo-600 text-white px-6 py-3 rounded-md font-medium hover:bg-indigo-700 transition">
                            Valider le classement
                        </button>
                    </div>
                </div>

                <!-- History Tab -->
                <div id="history" class="tab-content">
                    <div class="mb-6 flex justify-between items-center">
                        <h2 class="text-xl font-semibold text-gray-800">Historique des classements</h2>
                        <select id="history-week-select" class="border rounded-md px-3 py-2 text-sm">
                            <!-- Options will be added by JS -->
                        </select>
                    </div>

                    <div id="history-content" class="space-y-4">
                        <!-- History will be loaded by JS -->
                    </div>
                </div>

                <!-- Evolution Tab -->
                <div id="evolution" class="tab-content">
                    <div class="mb-6">
                        <h2 class="text-xl font-semibold text-gray-800">Évolution des classements</h2>
                        <p class="text-gray-600 text-sm mt-1">Analyse des tendances sur plusieurs semaines</p>
                    </div>

                    <div class="grid grid-cols-1 gap-6">
                        <div class="bg-white p-4 rounded-lg border border-gray-200 hovered-element">
                            <canvas id="evolution-chart" height="500" width="800" class="hovered-element" style="display: block; box-sizing: border-box; height: 500px; width: 800px;"></canvas>
                        </div>
                        <div class="bg-white p-4 rounded-lg border border-gray-200">
                            <h3 class="font-medium text-gray-800 mb-3">Tendances récentes</h3>
                            <div id="trends-list" class="space-y-3">
                                <!-- Trends will be added by JS -->
                            </div>
                        </div>
                    </div>

                    <div class="mt-6 flex justify-end space-x-3">
                        <button id="export-csv-btn" class="bg-gray-100 text-gray-700 px-4 py-2 rounded-md text-sm font-medium hover:bg-gray-200 border border-gray-300">
                            Exporter CSV
                        </button>
                        <button id="export-pdf-btn" class="bg-indigo-600 text-white px-4 py-2 rounded-md text-sm font-medium hover:bg-indigo-700">
                            Exporter PDF
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script>
        // Database simulation using localStorage
        const DB_NAME = 'kip_pic_rankings';
        
        // Initialize database if not exists
        if (!localStorage.getItem(DB_NAME)) {
            localStorage.setItem(DB_NAME, JSON.stringify({
                weeks: [],
                rankings: {}
            }));
        }

        // Get database
        function getDB() {
            return JSON.parse(localStorage.getItem(DB_NAME));
        }

        // Update database
        function updateDB(data) {
            localStorage.setItem(DB_NAME, JSON.stringify(data));
        }

        // Blocks definition
        let BLOCKS = [
            { id: 'primo-info', name: 'Primo-info', color: 'bg-blue-100', text: 'text-blue-800' },
            { id: 'conseil', name: 'Conseil', color: 'bg-green-100', text: 'text-green-800' },
            { id: 'langue', name: 'Langue', color: 'bg-yellow-100', text: 'text-yellow-800' },
            { id: 'petite-enfance', name: 'Petite-enfance', color: 'bg-red-100', text: 'text-red-800' },
            { id: 'employabilite', name: 'Employabilité', color: 'bg-purple-100', text: 'text-purple-800' },
            { id: 'vivre-ensemble', name: 'Vivre ensemble', color: 'bg-pink-100', text: 'text-pink-800' }
        ];

        // Current state
        let currentWeek = '';
        let currentRanking = [];
        let isDragging = false;
        let draggedItem = null;

        // DOM Elements
        const tabBtns = document.querySelectorAll('.tab-btn');
        const tabContents = document.querySelectorAll('.tab-content');
        const blocksContainer = document.getElementById('blocks-container');
        const validateBtn = document.getElementById('validate-btn');
        const weekSelect = document.getElementById('week-select');
        const newWeekBtn = document.getElementById('new-week-btn');
        const historyWeekSelect = document.getElementById('history-week-select');
        const historyContent = document.getElementById('history-content');
        const trendsList = document.getElementById('trends-list');
        const exportCsvBtn = document.getElementById('export-csv-btn');
        const exportPdfBtn = document.getElementById('export-pdf-btn');

        // Initialize the app
        function initApp() {
            loadWeeks();
            setupTabs();
            setupDragAndDrop();
            setupEventListeners();
            showCurrentWeekRanking();
            
            // Setup block selection
            document.getElementById('apply-blocks-btn').addEventListener('click', () => {
                const selectedBlocks = [];
                if (document.getElementById('primo-info').checked) selectedBlocks.push('primo-info');
                if (document.getElementById('conseil').checked) selectedBlocks.push('conseil');
                if (document.getElementById('langue').checked) selectedBlocks.push('langue');
                if (document.getElementById('petite-enfance').checked) selectedBlocks.push('petite-enfance');
                if (document.getElementById('employabilite').checked) selectedBlocks.push('employabilite');
                if (document.getElementById('vivre-ensemble').checked) selectedBlocks.push('vivre-ensemble');
                
                if (selectedBlocks.length < 2) {
                    alert('Veuillez sélectionner au moins 2 blocs');
                    return;
                }
                
                // Update BLOCKS array with only selected blocks
                BLOCKS = [
                    { id: 'primo-info', name: 'Primo-info', color: 'bg-blue-100', text: 'text-blue-800' },
                    { id: 'conseil', name: 'Conseil', color: 'bg-green-100', text: 'text-green-800' },
                    { id: 'langue', name: 'Langue', color: 'bg-yellow-100', text: 'text-yellow-800' },
                    { id: 'petite-enfance', name: 'Petite-enfance', color: 'bg-red-100', text: 'text-red-800' },
                    { id: 'employabilite', name: 'Employabilité', color: 'bg-purple-100', text: 'text-purple-800' },
                    { id: 'vivre-ensemble', name: 'Vivre ensemble', color: 'bg-pink-100', text: 'text-pink-800' }
                ].filter(block => selectedBlocks.includes(block.id));
                
                // Reset current ranking with selected blocks
                currentRanking = BLOCKS.map(block => block.id);
                renderBlocks(currentRanking);
                
                // Update database if current week exists
                const db = getDB();
                if (currentWeek && db.rankings[currentWeek]) {
                    db.rankings[currentWeek] = currentRanking;
                    updateDB(db);
                }
                
                // Refresh charts if on evolution tab
                if (document.getElementById('evolution').classList.contains('active')) {
                    renderEvolutionChart();
                    renderTrends();
                }
            });
        }

        // Setup tab navigation
        function setupTabs() {
            tabBtns.forEach(btn => {
                btn.addEventListener('click', () => {
                    // Remove active class from all tabs
                    tabBtns.forEach(b => {
                        b.classList.remove('text-indigo-600', 'border-indigo-600');
                        b.classList.add('text-gray-500');
                    });
                    
                    // Add active class to clicked tab
                    btn.classList.add('text-indigo-600', 'border-indigo-600');
                    btn.classList.remove('text-gray-500');
                    
                    // Hide all tab contents
                    tabContents.forEach(content => content.classList.remove('active'));
                    
                    // Show selected tab content
                    const tabId = btn.getAttribute('data-tab');
                    document.getElementById(tabId).classList.add('active');
                    
                    // Load data if needed
                    if (tabId === 'history') {
                        loadHistoryWeek();
                    } else if (tabId === 'evolution') {
                        renderEvolutionChart();
                        renderTrends();
                    }
                });
            });
        }

        // Load available weeks
        function loadWeeks() {
            const db = getDB();
            weekSelect.innerHTML = '';
            historyWeekSelect.innerHTML = '';
            
            if (db.weeks.length === 0) {
                weekSelect.innerHTML = '<option value="">Aucune semaine disponible</option>';
                historyWeekSelect.innerHTML = '<option value="">Aucune semaine disponible</option>';
                currentWeek = '';
                return;
            }
            
            db.weeks.forEach(week => {
                const option = document.createElement('option');
                option.value = week;
                option.textContent = `Semaine ${week}`;
                weekSelect.appendChild(option.cloneNode(true));
                historyWeekSelect.appendChild(option);
            });
            
            currentWeek = db.weeks[db.weeks.length - 1];
            weekSelect.value = currentWeek;
            historyWeekSelect.value = currentWeek;
        }

        // Show current week ranking
        function showCurrentWeekRanking() {
            const db = getDB();
            
            if (db.weeks.length === 0) {
                blocksContainer.innerHTML = '<p class="text-gray-500 text-center py-8">Aucun classement disponible. Créez une nouvelle semaine.</p>';
                return;
            }
            
            currentWeek = db.weeks[db.weeks.length - 1];
            weekSelect.value = currentWeek;
            
            if (db.rankings[currentWeek]) {
                currentRanking = db.rankings[currentWeek];
                renderBlocks(currentRanking);
            } else {
                // New week, initialize with default order
                currentRanking = BLOCKS.map(block => block.id);
                renderBlocks(currentRanking);
            }
        }

        // Render blocks in the container
        function renderBlocks(order) {
            blocksContainer.innerHTML = '';
            
            order.forEach((blockId, index) => {
                const block = BLOCKS.find(b => b.id === blockId);
                if (block) {
                    const blockElement = document.createElement('div');
                    blockElement.className = `drag-item flex items-center p-4 rounded-lg cursor-move ${block.color} ${block.text} border border-transparent hover:border-gray-300`;
                    blockElement.setAttribute('draggable', 'true');
                    blockElement.setAttribute('data-id', block.id);
                    
                    blockElement.innerHTML = `
                        <div class="w-8 h-8 flex items-center justify-center bg-white rounded-full mr-4 font-medium">${index + 1}</div>
                        <div class="flex-1 font-medium">${block.name}</div>
                        <svg class="w-5 h-5 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 8h16M4 16h16"></path>
                        </svg>
                    `;
                    
                    blocksContainer.appendChild(blockElement);
                }
            });
        }

        // Setup drag and drop functionality
        function setupDragAndDrop() {
            blocksContainer.addEventListener('dragstart', (e) => {
                if (e.target.classList.contains('drag-item')) {
                    isDragging = true;
                    draggedItem = e.target;
                    e.target.classList.add('dragging');
                    e.dataTransfer.effectAllowed = 'move';
                    e.dataTransfer.setData('text/html', e.target.innerHTML);
                }
            });

            blocksContainer.addEventListener('dragend', (e) => {
                if (e.target.classList.contains('drag-item')) {
                    isDragging = false;
                    e.target.classList.remove('dragging');
                }
            });

            blocksContainer.addEventListener('dragover', (e) => {
                if (isDragging) {
                    e.preventDefault();
                    const afterElement = getDragAfterElement(blocksContainer, e.clientY);
                    const draggable = document.querySelector('.dragging');
                    
                    if (afterElement == null) {
                        blocksContainer.appendChild(draggable);
                    } else {
                        blocksContainer.insertBefore(draggable, afterElement);
                    }
                    
                    // Update current ranking order
                    updateCurrentRankingOrder();
                }
            });
        }

        // Get the element after which the dragged item should be placed
        function getDragAfterElement(container, y) {
            const draggableElements = [...container.querySelectorAll('.drag-item:not(.dragging)')];
            
            return draggableElements.reduce((closest, child) => {
                const box = child.getBoundingClientRect();
                const offset = y - box.top - box.height / 2;
                
                if (offset < 0 && offset > closest.offset) {
                    return { offset: offset, element: child };
                } else {
                    return closest;
                }
            }, { offset: Number.NEGATIVE_INFINITY }).element;
        }

        // Update current ranking order based on DOM
        function updateCurrentRankingOrder() {
            const blockElements = blocksContainer.querySelectorAll('.drag-item');
            currentRanking = Array.from(blockElements).map(el => el.getAttribute('data-id'));
        }

        // Setup event listeners
        function setupEventListeners() {
            // Validate ranking
            validateBtn.addEventListener('click', () => {
                if (currentWeek === '') {
                    alert('Veuillez sélectionner ou créer une semaine');
                    return;
                }
                
                const db = getDB();
                db.rankings[currentWeek] = currentRanking;
                updateDB(db);
                
                alert(`Classement de la semaine ${currentWeek} enregistré avec succès !`);
                
                // Create new week automatically
                let weekNumber = parseInt(currentWeek) + 1;
                const newWeek = weekNumber.toString();
                db.weeks.push(newWeek);
                db.rankings[newWeek] = BLOCKS.map(block => block.id);
                updateDB(db);
                
                loadWeeks();
                currentWeek = newWeek;
                weekSelect.value = newWeek;
                currentRanking = db.rankings[newWeek];
                renderBlocks(currentRanking);
            });
            
            // Week selection change
            weekSelect.addEventListener('change', (e) => {
                currentWeek = e.target.value;
                const db = getDB();
                
                if (db.rankings[currentWeek]) {
                    currentRanking = db.rankings[currentWeek];
                    renderBlocks(currentRanking);
                } else {
                    currentRanking = BLOCKS.map(block => block.id);
                    renderBlocks(currentRanking);
                }
            });
            
            // New week button
            newWeekBtn.addEventListener('click', () => {
                const db = getDB();
                let weekNumber = 1;
                
                if (db.weeks.length > 0) {
                    const lastWeek = db.weeks[db.weeks.length - 1];
                    weekNumber = parseInt(lastWeek) + 1;
                }
                
                const newWeek = weekNumber.toString();
                db.weeks.push(newWeek);
                db.rankings[newWeek] = BLOCKS.map(block => block.id);
                updateDB(db);
                
                loadWeeks();
                currentWeek = newWeek;
                weekSelect.value = newWeek;
                currentRanking = db.rankings[newWeek];
                renderBlocks(currentRanking);
                
                // Switch to ranking tab
                tabBtns[0].click();
            });
            
            // History week selection change
            historyWeekSelect.addEventListener('change', loadHistoryWeek);
            
            // Export buttons
            exportCsvBtn.addEventListener('click', exportToCsv);
            exportPdfBtn.addEventListener('click', exportToPdf);
        }

        // Load history for selected week
        function loadHistoryWeek() {
            const week = historyWeekSelect.value;
            const db = getDB();
            
            if (!week || !db.rankings[week]) {
                historyContent.innerHTML = '<p class="text-gray-500 text-center py-8">Aucun classement disponible pour cette semaine.</p>';
                return;
            }
            
            const ranking = db.rankings[week];
            let html = `
                <h3 class="text-lg font-medium text-gray-800 mb-4">Classement de la semaine ${week}</h3>
                <div class="space-y-3">
            `;
            
            ranking.forEach((blockId, index) => {
                const block = BLOCKS.find(b => b.id === blockId);
                if (block) {
                    html += `
                        <div class="flex items-center p-3 rounded-lg ${block.color} ${block.text}">
                            <div class="w-8 h-8 flex items-center justify-center bg-white rounded-full mr-4 font-medium">${index + 1}</div>
                            <div class="flex-1 font-medium">${block.name}</div>
                        </div>
                    `;
                }
            });
            
            html += '</div>';
            historyContent.innerHTML = html;
        }

        // Render evolution chart
        function renderEvolutionChart() {
            const db = getDB();
            const ctx = document.getElementById('evolution-chart').getContext('2d');
            
            if (db.weeks.length < 1) {
                document.getElementById('evolution-chart').innerHTML = `
                    <p class="text-gray-500 text-center py-8">Pas assez de données pour afficher l'évolution</p>
                `;
                return;
            }
            
            // Prepare data for Chart.js - show all domains even if not selected
            const allBlocks = [
                { id: 'primo-info', name: 'Primo-info', color: 'bg-blue-100', text: 'text-blue-800' },
                { id: 'conseil', name: 'Conseil', color: 'bg-green-100', text: 'text-green-800' },
                { id: 'langue', name: 'Langue', color: 'bg-yellow-100', text: 'text-yellow-800' },
                { id: 'petite-enfance', name: 'Petite-enfance', color: 'bg-red-100', text: 'text-red-800' },
                { id: 'employabilite', name: 'Employabilité', color: 'bg-purple-100', text: 'text-purple-800' },
                { id: 'vivre-ensemble', name: 'Vivre ensemble', color: 'bg-pink-100', text: 'text-pink-800' }
            ];
            
            const labels = db.weeks.map(w => `Semaine ${w}`);
            const datasets = allBlocks.map(block => {
                const data = db.weeks.map(week => {
                    if (db.rankings[week]) {
                        const position = db.rankings[week].indexOf(block.id) + 1;
                        return position || null;
                    }
                    return null;
                });
                
                return {
                    label: block.name,
                    data: data,
                    backgroundColor: block.text.replace('text-', 'bg-').replace('-800', '-500'),
                    borderColor: block.text.replace('text-', 'bg-').replace('-800', '-700'),
                    borderWidth: 2,
                    tension: 0.1,
                    fill: false,
                    hidden: !BLOCKS.some(b => b.id === block.id) // Hide if not selected
                };
            });
            
            // Destroy previous chart if exists
            if (window.evolutionChart) {
                window.evolutionChart.destroy();
            }
            
            // Calculate weighted scores for each block (higher score for better ranks)
            const weightedScores = {};
            allBlocks.forEach(block => {
                weightedScores[block.id] = 0;
            });

            db.weeks.forEach(week => {
                if (db.rankings[week]) {
                    const numBlocks = db.rankings[week].length;
                    db.rankings[week].forEach((blockId, index) => {
                        // Higher score for better ranks (1st place gets max points)
                        weightedScores[blockId] += (numBlocks - index);
                    });
                }
            });

            // Prepare data for horizontal bar chart
            const sortedBlocks = allBlocks
                .map(block => ({
                    ...block,
                    score: weightedScores[block.id],
                    // Generate darker color for bars
                    barColor: block.text.replace('text-', 'bg-').replace('-800', '-600')
                }))
                .sort((a, b) => b.score - a.score);

            // Calculate percentages instead of raw scores
            const totalScore = sortedBlocks.reduce((sum, block) => sum + block.score, 0);
            const percentages = sortedBlocks.map(block => Math.round((block.score / totalScore) * 100));

            window.evolutionChart = new Chart(ctx, {
                type: 'bar',
                data: {
                    labels: sortedBlocks.map(block => block.name),
                    datasets: [{
                        label: 'Répartition des priorités (%)',
                        data: percentages,
                        backgroundColor: sortedBlocks.map(block => block.barColor),
                        borderColor: sortedBlocks.map(block => block.barColor.replace('bg-', 'border-').replace('-500', '-700')),
                        borderWidth: 1
                    }]
                },
                plugins: [{
                    id: 'percentageLabels',
                    afterDatasetsDraw(chart, args, options) {
                        const {ctx, data, chartArea: {top, bottom, left, right, width, height}, scales: {x, y}} = chart;
                        
                        ctx.font = 'bold 12px sans-serif';
                        ctx.textAlign = 'center';
                        ctx.textBaseline = 'middle';
                        
                        data.datasets.forEach((dataset, i) => {
                            chart.getDatasetMeta(i).data.forEach((bar, index) => {
                                const value = dataset.data[index];
                                ctx.fillStyle = '#000';
                                ctx.fillText(`${value}%`, bar.x, bar.y - 10);
                            });
                        });
                    }
                }],
                options: {
                    indexAxis: 'x',
                    responsive: true,
                    maintainAspectRatio: false,
                    animation: {
                        onComplete: function() {
                            const chart = this;
                            const ctx = chart.ctx;
                            ctx.font = 'bold 12px sans-serif';
                            ctx.textAlign = 'center';
                            ctx.textBaseline = 'middle';
                            
                            this.data.datasets.forEach((dataset, i) => {
                                const meta = chart.getDatasetMeta(i);
                                meta.data.forEach((bar, index) => {
                                    const data = dataset.data[index];
                                    ctx.fillStyle = '#000';
                                    ctx.fillText(`${data}%`, bar.x, bar.y - 10);
                                });
                            });
                        }
                    },
                    scales: {
                        y: {
                            beginAtZero: true,
                            max: 100,
                            title: {
                                display: true,
                                text: 'Pourcentage (%)',
                                font: {
                                    size: 14,
                                    weight: 'bold'
                                }
                            },
                            ticks: {
                                font: {
                                    size: 12
                                }
                            }
                        },
                        x: {
                            title: {
                                display: true,
                                text: 'Blocs',
                                font: {
                                    size: 14,
                                    weight: 'bold'
                                }
                            },
                            ticks: {
                                font: {
                                    size: 12
                                }
                            }
                        }
                    },
                    plugins: {
                        tooltip: {
                            callbacks: {
                                label: function(context) {
                                    return `Score: ${context.parsed.x}`;
                                }
                            },
                            bodyFont: {
                                size: 12
                            },
                            titleFont: {
                                size: 14
                            }
                        },
                        legend: {
                            display: false
                        },
                        datalabels: {
                            display: false
                        }
                    },
                    layout: {
                        padding: {
                            left: 20,
                            right: 20,
                            top: 20,
                            bottom: 20
                        }
                    },
                    barPercentage: 0.8,
                    categoryPercentage: 0.9
                }
            });
        }

        // Render trends list
        function renderTrends() {
            const db = getDB();
            
            if (db.weeks.length < 1) {
                trendsList.innerHTML = `
                    <p class="text-gray-500 text-sm">Pas assez de données pour afficher les tendances</p>
                `;
                return;
            }
            
            let html = '';
            const allBlocks = [
                { id: 'primo-info', name: 'Primo-info', color: 'bg-blue-100', text: 'text-blue-800' },
                { id: 'conseil', name: 'Conseil', color: 'bg-green-100', text: 'text-green-800' },
                { id: 'langue', name: 'Langue', color: 'bg-yellow-100', text: 'text-yellow-800' },
                { id: 'petite-enfance', name: 'Petite-enfance', color: 'bg-red-100', text: 'text-red-800' },
                { id: 'employabilite', name: 'Employabilité', color: 'bg-purple-100', text: 'text-purple-800' },
                { id: 'vivre-ensemble', name: 'Vivre ensemble', color: 'bg-pink-100', text: 'text-pink-800' }
            ];
            
            // Show trends for all domains, not just selected ones
            allBlocks.forEach(block => {
                let trendInfo = '';
                let trendIcon = '';
                let trendClass = 'text-gray-400';
                
                if (db.weeks.length >= 2) {
                    // Get last 4 weeks (or all available if less than 4)
                    const weeksToAnalyze = db.weeks.slice(-4);
                    const positions = [];
                    
                    // Get positions for each week
                    weeksToAnalyze.forEach(week => {
                        if (db.rankings[week]) {
                            const pos = db.rankings[week].indexOf(block.id) + 1;
                            if (pos) positions.push(pos);
                        }
                    });
                    
                    if (positions.length >= 2) {
                        // Calculate trend based on linear regression of last 4 positions
                        const n = positions.length;
                        let sumX = 0, sumY = 0, sumXY = 0, sumX2 = 0;
                        
                        positions.forEach((y, i) => {
                            const x = i + 1;
                            sumX += x;
                            sumY += y;
                            sumXY += x * y;
                            sumX2 += x * x;
                        });
                        
                        const slope = (n * sumXY - sumX * sumY) / (n * sumX2 - sumX * sumX);
                        
                        if (slope < -0.1) {
                            trendIcon = '⬆️';
                            trendClass = 'trend-up';
                            trendInfo = 'Amélioration';
                        } else if (slope > 0.1) {
                            trendIcon = '⬇️';
                            trendClass = 'trend-down';
                            trendInfo = 'Baisse';
                        } else {
                            trendIcon = '➡️';
                            trendClass = 'trend-stable';
                            trendInfo = 'Stable';
                        }
                    } else if (positions.length === 0) {
                        // If block was not selected in current week, mark as decreasing
                        trendIcon = '⬇️';
                        trendClass = 'trend-down';
                        trendInfo = 'Baisse';
                    }
                }
                
                html += `
                    <div class="flex items-center justify-between ${BLOCKS.some(b => b.id === block.id) ? '' : 'opacity-50'}">
                        <div class="font-medium ${block.text}">${block.name}</div>
                        <div class="flex items-center space-x-2">
                            ${trendInfo ? `<span class="text-sm ${trendClass}">${trendInfo}</span>` : ''}
                            <span class="${trendClass}">${trendIcon || '-'}</span>
                        </div>
                    </div>
                `;
            });
            
            trendsList.innerHTML = html;
        }

        // Export to CSV
        function exportToCsv() {
            const db = getDB();
            
            if (db.weeks.length === 0) {
                alert('Aucune donnée à exporter');
                return;
            }
            
            let csv = 'Semaine,' + BLOCKS.map(b => b.name).join(',') + '\n';
            
            db.weeks.forEach(week => {
                if (db.rankings[week]) {
                    const positions = BLOCKS.map(block => {
                        return db.rankings[week].indexOf(block.id) + 1;
                    });
                    csv += `Semaine ${week},${positions.join(',')}\n`;
                }
            });
            
            const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
            const url = URL.createObjectURL(blob);
            const link = document.createElement('a');
            link.setAttribute('href', url);
            link.setAttribute('download', `classement_kip_pic_${new Date().toISOString().slice(0, 10)}.csv`);
            link.style.visibility = 'hidden';
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
        }

        // Export to PDF
        function exportToPdf() {
            const { jsPDF } = window.jspdf;
            const doc = new jsPDF();
            
            // Add title
            doc.setFontSize(18);
            doc.text('Classement Kip-Pic Suisse', 105, 15, { align: 'center' });
            
            // Add date
            doc.setFontSize(10);
            doc.text(`Export du ${new Date().toLocaleDateString()}`, 105, 22, { align: 'center' });
            
            // Add evolution chart if available
            const db = getDB();
            if (db.weeks.length >= 2) {
                doc.setFontSize(14);
                doc.text('Évolution des positions', 105, 35, { align: 'center' });
                
                // Get chart canvas
                const canvas = document.getElementById('evolution-chart');
                if (canvas) {
                    const canvasImage = canvas.toDataURL('image/png', 1.0);
                    doc.addImage(canvasImage, 'PNG', 15, 45, 180, 100);
                }
            }
            
            // Add current ranking
            doc.setFontSize(16);
            doc.text('Classement actuel', 105, 170, { align: 'center' });
            
            if (currentWeek && db.rankings[currentWeek]) {
                const ranking = db.rankings[currentWeek];
                ranking.forEach((blockId, index) => {
                    const block = BLOCKS.find(b => b.id === blockId);
                    if (block) {
                        doc.setFontSize(14);
                        doc.setTextColor(block.text.replace('text-', '').replace('-800', '-700'));
                        doc.text(`${index + 1}. ${block.name}`, 20, 185 + (index * 10));
                        doc.setTextColor('#000000'); // Reset to black
                    }
                });
            }
            
            // Save the PDF
            doc.save(`classement_kip_pic_${new Date().toISOString().slice(0, 10)}.pdf`);
        }

        // Initialize the app when DOM is loaded
        document.addEventListener('DOMContentLoaded', initApp);
    </script>
<p style="border-radius: 8px; text-align: center; font-size: 12px; color: #fff; margin-top: 16px;position: fixed; left: 8px; bottom: 8px; z-index: 10; background: rgba(0, 0, 0, 0.8); padding: 4px 8px;">Made with <img src="https://enzostvs-deepsite.hf.space/logo.svg" alt="DeepSite Logo" style="width: 16px; height: 16px; vertical-align: middle;display:inline-block;margin-right:3px;filter:brightness(0) invert(1);"><a href="https://enzostvs-deepsite.hf.space" style="color: #fff;text-decoration: underline;" target="_blank" >DeepSite</a> - 🧬 <a href="https://enzostvs-deepsite.hf.space?remix=masterseb/pic2" style="color: #fff;text-decoration: underline;" target="_blank" >Remix</a></p></body>
</html>