File size: 60,674 Bytes
23e063a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0481019
 
23e063a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f8c3a4a
 
 
 
23e063a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f8c3a4a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
23e063a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0481019
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
23e063a
0481019
 
 
 
 
 
 
 
23e063a
 
 
 
 
0481019
23e063a
0481019
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
23e063a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0481019
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
23e063a
 
 
 
0481019
 
23e063a
 
 
 
 
 
 
 
 
 
 
 
 
 
0481019
 
b56a800
 
 
0481019
 
 
 
 
23e063a
 
 
 
 
0481019
 
 
 
 
23e063a
 
0481019
 
 
 
 
23e063a
 
0481019
 
 
 
b56a800
23e063a
 
 
 
 
0481019
 
23e063a
0481019
 
 
23e063a
 
0481019
23e063a
 
 
0481019
23e063a
0481019
23e063a
0481019
23e063a
0481019
23e063a
f8c3a4a
 
 
 
 
 
23e063a
 
 
 
0481019
 
23e063a
 
0481019
23e063a
 
0481019
23e063a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0481019
 
23e063a
0481019
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
23e063a
 
0481019
 
 
 
 
 
 
 
 
 
23e063a
0481019
 
 
 
 
 
 
 
 
 
 
 
23e063a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f8c3a4a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0481019
23e063a
0481019
 
 
 
 
 
 
 
 
 
 
 
 
 
 
23e063a
 
0481019
 
23e063a
 
 
 
 
 
 
 
 
 
 
 
 
 
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
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
<!DOCTYPE html>
<html lang="fr">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Gestion des Appareils - ComSync Pro</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <script src="https://unpkg.com/feather-icons"></script>
    <script src="https://cdn.jsdelivr.net/npm/feather-icons/dist/feather.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/vanta@latest/dist/vanta.net.min.js"></script>
    <link rel="stylesheet" href="style.css">
    <style>
        .device-type-tab {
            transition: all 0.3s ease;
        }
        .device-type-tab.active {
            background: rgba(59, 130, 246, 0.2);
            border-color: #3b82f6;
            color: #3b82f6;
        }
        .qr-scanner {
            background: repeating-linear-gradient(
                0deg,
                rgba(0,0,0,0.15),
                rgba(0,0,0,0.15) 1px,
                transparent 1px,
                transparent 2px
            );
            animation: scan 2s linear infinite;
        }
        @keyframes scan {
            0% { background-position: 0 0; }
            100% { background-position: 0 100px; }
        }
        .status-badge {
            display: inline-flex;
            align-items: center;
            padding: 0.25rem 0.75rem;
            border-radius: 9999px;
            font-size: 0.75rem;
            font-weight: 500;
        }
        .status-online { background: rgba(16, 185, 129, 0.2); color: #10b981; }
        .status-offline { background: rgba(239, 68, 68, 0.2); color: #ef4444; }
        .status-pending { background: rgba(245, 158, 11, 0.2); color: #f59e0b; }
        .brand-logo {
            width: 40px;
            height: 40px;
            display: flex;
            align-items: center;
            justify-content: center;
            border-radius: 8px;
            font-weight: bold;
            font-size: 0.75rem;
        }
    </style>
</head>
<body class="bg-gray-900 text-gray-100">
    <div id="vanta-bg" class="fixed inset-0 z-0"></div>
    
    <script src="components/navbar.js"></script>
    <custom-navbar></custom-navbar>
    
    <div class="relative z-10 min-h-screen p-4 md:p-6">
        <!-- Header -->
        <header class="bg-gray-800/80 backdrop-blur-md rounded-xl p-4 mb-6 border border-gray-700/50 shadow-lg">
            <div class="flex flex-col md:flex-row justify-between items-start md:items-center gap-4">
                <div>
                    <h1 class="text-2xl font-bold bg-gradient-to-r from-blue-400 to-purple-400 bg-clip-text text-transparent">Gestion des Appareils</h1>
                    <p class="text-gray-400 text-sm mt-1" id="company-info">Société : <span class="text-white">Chargement...</span></p>
                </div>
                <div class="flex items-center gap-3">
                    <div class="bg-gray-700/50 rounded-lg p-2 flex items-center space-x-3">
                        <span class="text-sm text-gray-400">ID Société:</span>
                        <span class="font-mono text-sm text-blue-400" id="company-id-display">-</span>
                        <button onclick="copyCompanyId()" class="text-gray-400 hover:text-white">
                            <i data-feather="copy" class="w-4 h-4"></i>
                        </button>
                    </div>
                    <button onclick="openImeiConnectModal()" class="px-4 py-2 bg-green-600 hover:bg-green-700 rounded-lg text-sm font-medium flex items-center gap-2 transition-colors">
                        <i data-feather="hash" class="w-4 h-4"></i>
                        Connexion IMEI
                    </button>
                    <button onclick="openAddDeviceModal()" class="btn-primary flex items-center">
                        <i data-feather="plus" class="w-4 h-4 mr-2"></i>
                        Ajouter Appareil
                    </button>
                </div>
            </div>
        </header>

        <!-- Stats -->
        <div class="grid grid-cols-2 md:grid-cols-4 gap-4 mb-6">
            <div class="bg-gray-800/80 backdrop-blur-sm rounded-xl p-4 border border-gray-700/50">
                <div class="flex items-center justify-between mb-2">
                    <i data-feather="radio" class="w-5 h-5 text-green-400"></i>
                    <span class="text-xs text-gray-400">Talkies FM</span>
                </div>
                <p class="text-2xl font-bold" id="count-radios">0</p>
            </div>
            <div class="bg-gray-800/80 backdrop-blur-sm rounded-xl p-4 border border-gray-700/50">
                <div class="flex items-center justify-between mb-2">
                    <i data-feather="smartphone" class="w-5 h-5 text-blue-400"></i>
                    <span class="text-xs text-gray-400">Android</span>
                </div>
                <p class="text-2xl font-bold" id="count-android">0</p>
            </div>
            <div class="bg-gray-800/80 backdrop-blur-sm rounded-xl p-4 border border-gray-700/50">
                <div class="flex items-center justify-between mb-2">
                    <i data-feather="tablet" class="w-5 h-5 text-purple-400"></i>
                    <span class="text-xs text-gray-400">Tablettes</span>
                </div>
                <p class="text-2xl font-bold" id="count-tablets">0</p>
            </div>
            <div class="bg-gray-800/80 backdrop-blur-sm rounded-xl p-4 border border-gray-700/50">
                <div class="flex items-center justify-between mb-2">
                    <i data-feather="activity" class="w-5 h-5 text-green-400"></i>
                    <span class="text-xs text-gray-400">En ligne</span>
                </div>
                <p class="text-2xl font-bold" id="count-online">0</p>
            </div>
        </div>

        <!-- Tabs -->
        <div class="bg-gray-800/80 backdrop-blur-md rounded-xl p-2 mb-6 border border-gray-700/50">
            <div class="flex space-x-2 overflow-x-auto">
                <button onclick="switchTab('all')" class="device-type-tab active px-4 py-2 rounded-lg text-sm font-medium border border-transparent" id="tab-all">
                    Tous les appareils
                </button>
                <button onclick="switchTab('radios')" class="device-type-tab px-4 py-2 rounded-lg text-sm font-medium border border-transparent" id="tab-radios">
                    <i data-feather="radio" class="w-4 h-4 inline mr-1"></i> Talkies FM
                </button>
                <button onclick="switchTab('android')" class="device-type-tab px-4 py-2 rounded-lg text-sm font-medium border border-transparent" id="tab-android">
                    <i data-feather="smartphone" class="w-4 h-4 inline mr-1"></i> Android
                </button>
                <button onclick="switchTab('tablets')" class="device-type-tab px-4 py-2 rounded-lg text-sm font-medium border border-transparent" id="tab-tablets">
                    <i data-feather="tablet" class="w-4 h-4 inline mr-1"></i> Tablettes
                </button>
                <button onclick="switchTab('pending')" class="device-type-tab px-4 py-2 rounded-lg text-sm font-medium border border-transparent" id="tab-pending">
                    <i data-feather="clock" class="w-4 h-4 inline mr-1"></i> En attente
                </button>
            </div>
        </div>

        <!-- Devices Grid -->
        <div id="devices-container" class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
            <!-- Devices will be loaded here -->
        </div>

        <!-- Empty State -->
        <div id="empty-state" class="hidden text-center py-12">
            <i data-feather="smartphone" class="w-16 h-16 text-gray-600 mx-auto mb-4"></i>
            <h3 class="text-xl font-semibold text-gray-400 mb-2">Aucun appareil enregistré</h3>
            <p class="text-gray-500 mb-6">Commencez par ajouter votre premier appareil</p>
            <button onclick="openAddDeviceModal()" class="btn-primary">
                Ajouter un appareil
            </button>
        </div>
    </div>

    <!-- IMEI Connect Modal -->
    <div id="imei-connect-modal" class="fixed inset-0 bg-black/80 backdrop-blur-sm z-50 hidden flex items-center justify-center p-4">
        <div class="bg-gray-800 rounded-xl max-w-lg w-full border border-gray-700">
            <div class="p-6 border-b border-gray-700 flex justify-between items-center">
                <h2 class="text-xl font-semibold flex items-center gap-2">
                    <i data-feather="hash" class="w-5 h-5 text-green-400"></i>
                    Connexion par IMEI
                </h2>
                <button onclick="closeImeiConnectModal()" class="text-gray-400 hover:text-white">
                    <i data-feather="x" class="w-6 h-6"></i>
                </button>
            </div>
            <div class="p-6 space-y-5">
                <!-- IMEI Input -->
                <div>
                    <label class="block text-sm font-medium mb-2">Numéro IMEI *</label>
                    <div class="flex gap-2">
                        <input type="text" id="imei-search-input" class="flex-1 bg-gray-700 rounded-lg px-4 py-3 border border-gray-600 text-white font-mono text-lg tracking-widest focus:outline-none focus:border-green-500 focus:ring-2 focus:ring-green-500/20" placeholder="354601080768XXX" maxlength="15" oninput="formatImeiInput(this)">
                        <button onclick="scanImeiBarcode()" class="px-4 py-3 bg-gray-700 rounded-lg hover:bg-gray-600 transition-colors border border-gray-600" title="Scanner code-barres">
                            <i data-feather="scan" class="w-5 h-5 text-green-400"></i>
                        </button>
                    </div>
                    <p class="text-xs text-gray-500 mt-1">15 chiffres — Tapez *#06# sur l'appareil pour obtenir l'IMEI</p>
                </div>

                <!-- IMEI Validation Status -->
                <div id="imei-validation-status" class="hidden">
                    <div class="bg-gray-700/50 rounded-lg p-4 space-y-3">
                        <div class="flex items-center gap-3">
                            <div id="imei-valid-icon" class="w-10 h-10 rounded-full flex items-center justify-center">
                                <i data-feather="loader" class="w-5 h-5 animate-spin text-yellow-400"></i>
                            </div>
                            <div>
                                <p id="imei-valid-text" class="font-medium">Vérification en cours...</p>
                                <p id="imei-valid-sub" class="text-sm text-gray-400">Validation du numéro IMEI</p>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Connected Device Info (shown after successful connection) -->
                <div id="imei-connected-info" class="hidden">
                    <div class="bg-green-900/20 border border-green-700/50 rounded-lg p-4">
                        <div class="flex items-center gap-3 mb-3">
                            <div class="w-10 h-10 bg-green-600 rounded-full flex items-center justify-center">
                                <i data-feather="check" class="w-5 h-5 text-white"></i>
                            </div>
                            <div>
                                <p class="font-medium text-green-400">Appareil Connecté</p>
                                <p class="text-sm text-gray-400" id="imei-device-name"></p>
                            </div>
                        </div>
                        <div class="grid grid-cols-2 gap-3 text-sm">
                            <div class="bg-gray-800/50 rounded-lg p-2">
                                <p class="text-gray-500 text-xs">IMEI</p>
                                <p class="font-mono text-white" id="imei-device-imei"></p>
                            </div>
                            <div class="bg-gray-800/50 rounded-lg p-2">
                                <p class="text-gray-500 text-xs">Marque / Modèle</p>
                                <p class="text-white" id="imei-device-brand"></p>
                            </div>
                            <div class="bg-gray-800/50 rounded-lg p-2">
                                <p class="text-gray-500 text-xs">Statut</p>
                                <p class="text-green-400" id="imei-device-status">En ligne</p>
                            </div>
                            <div class="bg-gray-800/50 rounded-lg p-2">
                                <p class="text-gray-500 text-xs">Dernière activité</p>
                                <p class="text-white" id="imei-device-lastseen"></p>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Search in existing devices -->
                <div id="imei-search-results" class="hidden">
                    <h4 class="text-sm font-medium text-gray-300 mb-2">Appareils correspondants</h4>
                    <div id="imei-results-list" class="space-y-2 max-h-48 overflow-y-auto"></div>
                </div>

                <!-- Actions -->
                <div class="flex gap-3 pt-2">
                    <button onclick="searchImei()" class="flex-1 bg-blue-600 hover:bg-blue-700 py-3 rounded-lg font-medium flex items-center justify-center gap-2 transition-colors" id="imei-search-btn">
                        <i data-feather="search" class="w-4 h-4"></i>
                        Rechercher
                    </button>
                    <button onclick="connectByImei()" class="flex-1 bg-green-600 hover:bg-green-700 py-3 rounded-lg font-medium flex items-center justify-center gap-2 transition-colors" id="imei-connect-btn">
                        <i data-feather="link" class="w-4 h-4"></i>
                        Connecter
                    </button>
                </div>

                <!-- IMEI History -->
                <div class="border-t border-gray-700 pt-4">
                    <h4 class="text-sm font-medium text-gray-400 mb-2 flex items-center gap-2">
                        <i data-feather="clock" class="w-3 h-3"></i>
                        IMEI récents
                    </h4>
                    <div id="imei-history" class="flex flex-wrap gap-2"></div>
                </div>
            </div>
        </div>
    </div>

    <!-- Add Device Modal -->
    <div id="add-device-modal" class="fixed inset-0 bg-black/80 backdrop-blur-sm z-50 hidden flex items-center justify-center p-4">
        <div class="bg-gray-800 rounded-xl max-w-2xl w-full max-h-[90vh] overflow-y-auto border border-gray-700">
            <div class="p-6 border-b border-gray-700 flex justify-between items-center">
                <h2 class="text-xl font-semibold">Ajouter un nouvel appareil</h2>
                <button onclick="closeAddDeviceModal()" class="text-gray-400 hover:text-white">
                    <i data-feather="x" class="w-6 h-6"></i>
                </button>
            </div>
            
            <div class="p-6">
                <!-- Device Type Selection -->
                <div class="mb-6">
                    <label class="block text-sm font-medium mb-3">Type d'appareil *</label>
                    <div class="grid grid-cols-2 md:grid-cols-4 gap-3">
                        <button onclick="selectDeviceType('radio')" class="device-type-btn p-4 border border-gray-600 rounded-lg hover:border-blue-500 transition-all text-center" id="btn-type-radio">
                            <i data-feather="radio" class="w-8 h-8 mx-auto mb-2 text-green-400"></i>
                            <div class="text-sm font-medium">Talkie FM</div>
                        </button>
                        <button onclick="selectDeviceType('android')" class="device-type-btn p-4 border border-gray-600 rounded-lg hover:border-blue-500 transition-all text-center" id="btn-type-android">
                            <i data-feather="smartphone" class="w-8 h-8 mx-auto mb-2 text-blue-400"></i>
                            <div class="text-sm font-medium">Smartphone</div>
                        </button>
                        <button onclick="selectDeviceType('tablet')" class="device-type-btn p-4 border border-gray-600 rounded-lg hover:border-blue-500 transition-all text-center" id="btn-type-tablet">
                            <i data-feather="tablet" class="w-8 h-8 mx-auto mb-2 text-purple-400"></i>
                            <div class="text-sm font-medium">Tablette</div>
                        </button>
                        <button onclick="selectDeviceType('desktop')" class="device-type-btn p-4 border border-gray-600 rounded-lg hover:border-blue-500 transition-all text-center" id="btn-type-desktop">
                            <i data-feather="monitor" class="w-8 h-8 mx-auto mb-2 text-yellow-400"></i>
                            <div class="text-sm font-medium">PC/Mac</div>
                        </button>
                    </div>
                </div>

                <!-- Radio Specific Fields -->
                <div id="radio-fields" class="hidden space-y-4">
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                        <div>
                            <label class="block text-sm font-medium mb-2">Marque *</label>
                            <select id="radio-brand" class="w-full bg-gray-700 rounded-lg px-4 py-3 border border-gray-600">
                                <option value="">Sélectionner...</option>
                                <option value="Motorola">Motorola</option>
                                <option value="Kenwood">Kenwood</option>
                                <option value="Hytera">Hytera</option>
                                <option value="Icom">Icom</option>
                                <option value="Midland">Midland</option>
                                <option value="Retevis">Retevis</option>
                                <option value="Baofeng">Baofeng</option>
                                <option value="TYT">TYT</option>
                                <option value="Autre">Autre</option>
                            </select>
                        </div>
                        <div>
                            <label class="block text-sm font-medium mb-2">Modèle *</label>
                            <input type="text" id="radio-model" class="w-full bg-gray-700 rounded-lg px-4 py-3 border border-gray-600" placeholder="Ex: DP4400e">
                        </div>
                        <div>
                            <label class="block text-sm font-medium mb-2">Numéro de série / IMEI</label>
                            <input type="text" id="radio-serial" class="w-full bg-gray-700 rounded-lg px-4 py-3 border border-gray-600" placeholder="Numéro de série">
                        </div>
                        <div>
                            <label class="block text-sm font-medium mb-2">Fréquence par défaut (MHz)</label>
                            <input type="text" id="radio-freq" class="w-full bg-gray-700 rounded-lg px-4 py-3 border border-gray-600" placeholder="462.550">
                        </div>
                    </div>
                    <div>
                        <label class="block text-sm font-medium mb-2">Bluetooth MAC Address</label>
                        <input type="text" id="radio-mac" class="w-full bg-gray-700 rounded-lg px-4 py-3 border border-gray-600" placeholder="AA:BB:CC:DD:EE:FF">
                    </div>
                </div>

                <!-- Android/Tablet Fields -->
                <div id="android-fields" class="hidden space-y-4">
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                        <div>
                            <label class="block text-sm font-medium mb-2">Marque</label>
                            <select id="android-brand" class="w-full bg-gray-700 rounded-lg px-4 py-3 border border-gray-600">
                                <option value="">Sélectionner...</option>
                                <option value="Samsung">Samsung</option>
                                <option value="Google">Google Pixel</option>
                                <option value="Xiaomi">Xiaomi</option>
                                <option value="Huawei">Huawei</option>
                                <option value="Sony">Sony</option>
                                <option value="CAT">CAT (Caterpillar)</option>
                                <option value="Crosscall">Crosscall</option>
                                <option value="Autre">Autre</option>
                            </select>
                        </div>
                        <div>
                            <label class="block text-sm font-medium mb-2">Modèle</label>
                            <input type="text" id="android-model" class="w-full bg-gray-700 rounded-lg px-4 py-3 border border-gray-600" placeholder="Ex: Galaxy XCover Pro">
                        </div>
                    </div>
                    <div>
                        <label class="block text-sm font-medium mb-2">Numéro IMEI *</label>
                        <input type="text" id="android-imei" class="w-full bg-gray-700 rounded-lg px-4 py-3 border border-gray-600" placeholder="Tapez *#06# sur l'appareil">
                    </div>
                    <div class="bg-blue-900/20 border border-blue-700/50 rounded-lg p-4">
                        <div class="flex items-start space-x-3">
                            <i data-feather="info" class="w-5 h-5 text-blue-400 mt-0.5"></i>
                            <div class="text-sm">
                                <p class="text-blue-400 font-medium mb-1">Installation requise</p>
                                <p class="text-gray-300">L'appareil doit avoir l'application ComSync Pro installée. <a href="#" class="text-blue-400 hover:underline">Télécharger l'APK</a></p>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Common Fields -->
                <div class="space-y-4 mt-4">
                    <div>
                        <label class="block text-sm font-medium mb-2">Nom de l'appareil (pour l'identifier)</label>
                        <input type="text" id="device-name" class="w-full bg-gray-700 rounded-lg px-4 py-3 border border-gray-600" placeholder="Ex: Radio Sécurité Nord">
                    </div>
                    <div>
                        <label class="block text-sm font-medium mb-2">Assigné à (optionnel)</label>
                        <select id="device-assignee" class="w-full bg-gray-700 rounded-lg px-4 py-3 border border-gray-600">
                            <option value="">Non assigné</option>
                        </select>
                    </div>
                </div>

                <!-- QR Code Section -->
                <div class="mt-6 border-t border-gray-700 pt-6">
                    <h3 class="text-sm font-medium mb-4">Configuration rapide par QR Code</h3>
                    <div class="flex items-center space-x-4">
                        <div class="bg-white p-4 rounded-lg">
                            <!-- Simulated QR Code -->
                            <div class="w-32 h-32 bg-gray-900 rounded relative overflow-hidden">
                                <div class="absolute inset-0 qr-scanner"></div>
                                <div class="absolute inset-4 border-2 border-white rounded flex items-center justify-center">
                                    <i data-feather="smartphone" class="w-8 h-8 text-white"></i>
                                </div>
                            </div>
                        </div>
                        <div class="flex-1">
                            <p class="text-sm text-gray-400 mb-2">Scannez ce QR code avec l'appareil pour l'enregistrer automatiquement.</p>
                            <button onclick="generateNewQR()" class="text-blue-400 text-sm hover:underline flex items-center">
                                <i data-feather="refresh-cw" class="w-4 h-4 mr-1"></i>
                                Générer un nouveau code
                            </button>
                        </div>
                    </div>
                </div>
            </div>
            
            <div class="p-6 border-t border-gray-700 flex justify-end space-x-3">
                <button onclick="closeAddDeviceModal()" class="btn-secondary">Annuler</button>
                <button onclick="saveDevice()" class="btn-primary">Enregistrer l'appareil</button>
            </div>
        </div>
    </div>

    <!-- Device Details Modal -->
    <div id="device-details-modal" class="fixed inset-0 bg-black/80 backdrop-blur-sm z-50 hidden flex items-center justify-center p-4">
        <div class="bg-gray-800 rounded-xl max-w-lg w-full border border-gray-700" id="device-details-content">
            <!-- Content loaded dynamically -->
        </div>
    </div>

    <script>
        // Initialize Vanta avec gestion d'erreur
        let vantaInstance = null;
        try {
            if (typeof VANTA !== 'undefined' && document.getElementById('vanta-bg')) {
                vantaInstance = VANTA.NET({
                    el: "#vanta-bg",
                    mouseControls: true,
                    touchControls: true,
                    gyroControls: false,
                    minHeight: 200.00,
                    minWidth: 200.00,
                    scale: 1.00,
                    scaleMobile: 1.00,
                    color: 0x3b82f6,
                    backgroundColor: 0x111827,
                    points: 10.00,
                    maxDistance: 22.00,
                    spacing: 18.00
                });
            }
        } catch (e) {
            console.warn('Vanta.js non disponible:', e);
        }

        // Initialize Feather icons
        document.addEventListener('DOMContentLoaded', function() {
            setTimeout(function() {
                if (typeof feather !== 'undefined') {
                    feather.replace();
                }
            }, 100);
        });

        let currentTab = 'all';
        let selectedDeviceType = null;
        let companyData = null;

        // Load company data avec vérification null
        function loadCompanyData() {
            try {
                const data = localStorage.getItem('comsync_current_company');
                const companyInfo = document.getElementById('company-info');
                const companyIdDisplay = document.getElementById('company-id-display');
                
                if (data && companyInfo && companyIdDisplay) {
                    companyData = JSON.parse(data);
                    companyInfo.innerHTML = `Société : <span class="text-white font-semibold">${companyData.name || 'Sans nom'}</span>`;
                    companyIdDisplay.textContent = companyData.id || 'N/A';
                } else {
                    // Demo mode if no company registered
                    if (companyInfo) {
                        companyInfo.innerHTML = `Société : <span class="text-white font-semibold">Démo Mode</span>`;
                    }
                    if (companyIdDisplay) {
                        companyIdDisplay.textContent = 'DEMO-001';
                    }
                }
                loadDevices();
            } catch (e) {
                console.error('Erreur chargement données société:', e);
                // Mode dégradé
                const companyInfo = document.getElementById('company-info');
                const companyIdDisplay = document.getElementById('company-id-display');
                if (companyInfo) companyInfo.innerHTML = `Société : <span class="text-white font-semibold">Erreur chargement</span>`;
                if (companyIdDisplay) companyIdDisplay.textContent = 'ERROR';
                loadDevices();
            }
        }

        function copyCompanyId() {
            const id = document.getElementById('company-id-display').textContent;
            navigator.clipboard.writeText(id).then(() => {
                alert('ID copié dans le presse-papier !');
            });
        }

        function switchTab(tab) {
            currentTab = tab;
            
            // Update UI
            document.querySelectorAll('.device-type-tab').forEach(t => t.classList.remove('active'));
            document.getElementById(`tab-${tab}`).classList.add('active');
            
            loadDevices();
        }

        function loadDevices() {
            try {
                const devices = JSON.parse(localStorage.getItem('comsync_devices') || '[]');
                const container = document.getElementById('devices-container');
                const emptyState = document.getElementById('empty-state');
                
                if (!container || !emptyState) return;
                
                // Filter devices avec vérification
                let filtered = devices || [];
                if (currentTab !== 'all' && currentTab !== 'pending') {
                    const typeFilter = currentTab === 'radios' ? 'radio' : 
                                      currentTab === 'tablets' ? 'tablet' : 'android';
                    filtered = devices.filter(d => d && d.type === typeFilter);
                } else if (currentTab === 'pending') {
                    filtered = devices.filter(d => d && d.status === 'pending');
                }
                
                // Update counts avec vérification null
                const countRadios = document.getElementById('count-radios');
                const countAndroid = document.getElementById('count-android');
                const countTablets = document.getElementById('count-tablets');
                const countOnline = document.getElementById('count-online');
                
                if (countRadios) countRadios.textContent = devices.filter(d => d && d.type === 'radio').length;
                if (countAndroid) countAndroid.textContent = devices.filter(d => d && (d.type === 'android' || d.type === 'tablet')).length;
                if (countTablets) countTablets.textContent = devices.filter(d => d && d.type === 'tablet').length;
                if (countOnline) countOnline.textContent = devices.filter(d => d && d.status === 'online').length;
                
                if (filtered.length === 0) {
                    container.innerHTML = '';
                    emptyState.classList.remove('hidden');
                    return;
                }
                
                emptyState.classList.add('hidden');
                container.innerHTML = filtered.map(device => createDeviceCard(device)).join('');
                
                // Réinitialiser Feather icons
                setTimeout(() => {
                    if (typeof feather !== 'undefined') {
                        feather.replace();
                    }
                }, 50);
                
            } catch (e) {
                console.error('Erreur chargement appareils:', e);
                const container = document.getElementById('devices-container');
                if (container) {
                    container.innerHTML = '<div class="col-span-full text-center text-red-400">Erreur lors du chargement des appareils</div>';
                }
            }
        }

        function createDeviceCard(device) {
            if (!device || !device.id) return '';
            
            const icons = {
                radio: 'radio',
                android: 'smartphone',
                tablet: 'tablet',
                desktop: 'monitor'
            };
            
            const colors = {
                radio: 'green',
                android: 'blue',
                tablet: 'purple',
                desktop: 'yellow'
            };
            
            const deviceType = device.type || 'unknown';
            const deviceStatus = device.status || 'offline';
            const deviceBrand = (device.brand && String(device.brand)) || 'Inconnu';
            const deviceModel = (device.model && String(device.model)) || '';
            const deviceName = (device.name && String(device.name)) || 'Appareil sans nom';
            
            const statusClass = deviceStatus === 'online' ? 'status-online' : 
                               deviceStatus === 'pending' ? 'status-pending' : 'status-offline';
            const statusText = deviceStatus === 'online' ? 'En ligne' : 
                              deviceStatus === 'pending' ? 'En attente' : 'Hors ligne';
            
            const brandColors = {
                'Motorola': 'bg-blue-600',
                'Kenwood': 'bg-red-600',
                'Hytera': 'bg-orange-600',
                'Icom': 'bg-green-600',
                'Midland': 'bg-purple-600',
                'Retevis': 'bg-yellow-600',
                'Baofeng': 'bg-gray-600',
                'TYT': 'bg-indigo-600',
                'Samsung': 'bg-blue-500',
                'Google': 'bg-gray-600',
                'Xiaomi': 'bg-orange-500',
                'Huawei': 'bg-red-500',
                'Sony': 'bg-black',
                'CAT': 'bg-yellow-600',
                'Crosscall': 'bg-green-500'
            };
            
            const brandColor = brandColors[deviceBrand] || 'bg-gray-600';
            const iconName = icons[deviceType] || 'help-circle';
            const colorName = colors[deviceType] || 'gray';
            
            const shortId = device.id ? String(device.id).slice(-8) : 'UNKNOWN';
            
            return `
                <div class="bg-gray-800/80 backdrop-blur-sm rounded-xl p-5 border border-gray-700/50 hover:border-blue-500/50 transition-all cursor-pointer" onclick="showDeviceDetails('${device.id}')">
                    <div class="flex items-start justify-between mb-4">
                        <div class="flex items-center space-x-3">
                            <div class="brand-logo ${brandColor} text-white flex-shrink-0">
                                ${deviceBrand.substring(0, 2).toUpperCase()}
                            </div>
                            <div class="min-w-0 flex-1">
                                <h3 class="font-semibold truncate">${deviceName}</h3>
                                <p class="text-xs text-gray-400 truncate">${deviceBrand} ${deviceModel}</p>
                            </div>
                        </div>
                        <span class="status-badge ${statusClass} flex-shrink-0">${statusText}</span>
                    </div>
                    
                    <div class="grid grid-cols-2 gap-3 mb-4 text-sm">
                        <div class="bg-gray-700/50 rounded p-2 min-w-0">
                            <p class="text-gray-400 text-xs">ID</p>
                            <p class="font-mono text-xs truncate">${shortId}</p>
                        </div>
                        <div class="bg-gray-700/50 rounded p-2 min-w-0">
                            <p class="text-gray-400 text-xs">Dernier sync</p>
                            <p class="text-xs truncate">${device.lastSync || 'Jamais'}</p>
                        </div>
                        ${device.imei ? `
                        <div class="bg-gray-700/50 rounded p-2 min-w-0 col-span-2">
                            <p class="text-gray-400 text-xs">IMEI</p>
                            <p class="font-mono text-xs text-green-400">${device.imei}</p>
                        </div>
                        ` : ''}
                    </div>
                    
                    <div class="flex items-center justify-between pt-3 border-t border-gray-700">
                        <div class="flex items-center space-x-2">
                            <i data-feather="${iconName}" class="w-4 h-4 text-${colorName}-400"></i>
                            <span class="text-xs text-gray-400 capitalize">${deviceType}</span>
                        </div>
                        <div class="flex space-x-2">
                            <button onclick="event.stopPropagation(); toggleDeviceStatus('${device.id}')" class="p-2 hover:bg-gray-700 rounded transition-colors" title="Changer statut">
                                <i data-feather="power" class="w-4 h-4"></i>
                            </button>
                            <button onclick="event.stopPropagation(); deleteDevice('${device.id}')" class="p-2 hover:bg-gray-700 rounded text-red-400 transition-colors" title="Supprimer">
                                <i data-feather="trash-2" class="w-4 h-4"></i>
                            </button>
                        </div>
                    </div>
                </div>
            `;
        }

        function openAddDeviceModal() {
            document.getElementById('add-device-modal').classList.remove('hidden');
            selectDeviceType('radio');
        }

        function closeAddDeviceModal() {
            document.getElementById('add-device-modal').classList.add('hidden');
            // Reset form
            document.querySelectorAll('.device-type-btn').forEach(b => b.classList.remove('border-blue-500', 'bg-blue-900/20'));
            selectedDeviceType = null;
        }

        function selectDeviceType(type) {
            selectedDeviceType = type;
            
            // Update UI
            document.querySelectorAll('.device-type-btn').forEach(b => {
                b.classList.remove('border-blue-500', 'bg-blue-900/20');
            });
            document.getElementById(`btn-type-${type}`).classList.add('border-blue-500', 'bg-blue-900/20');
            
            // Show/hide specific fields
            document.getElementById('radio-fields').classList.add('hidden');
            document.getElementById('android-fields').classList.add('hidden');
            
            if (type === 'radio') {
                document.getElementById('radio-fields').classList.remove('hidden');
            } else if (type === 'android' || type === 'tablet') {
                document.getElementById('android-fields').classList.remove('hidden');
            }
        }

        function saveDevice() {
            if (!selectedDeviceType) {
                alert('Veuillez sélectionner un type d\'appareil');
                return;
            }
            
            try {
                const deviceId = 'DEV-' + Date.now().toString(36).toUpperCase();
                
                // Fonction utilitaire pour récupérer les valeurs
                const getInputValue = (id) => {
                    const el = document.getElementById(id);
                    return el ? el.value.trim() : '';
                };
                
                let deviceData = {
                    id: deviceId,
                    type: selectedDeviceType,
                    name: getInputValue('device-name'),
                    assignee: getInputValue('device-assignee'),
                    status: 'pending',
                    lastSync: null,
                    companyId: (companyData && companyData.id) ? companyData.id : 'DEMO-001',
                    createdAt: new Date().toISOString()
                };
                
                // Type specific data
                if (selectedDeviceType === 'radio') {
                    deviceData.brand = getInputValue('radio-brand');
                    deviceData.model = getInputValue('radio-model');
                    deviceData.serial = getInputValue('radio-serial');
                    deviceData.frequency = getInputValue('radio-freq');
                    deviceData.macAddress = getInputValue('radio-mac');
                    
                    if (!deviceData.brand || !deviceData.model) {
                        alert('Veuillez remplir la marque et le modèle');
                        return;
                    }
                } else {
                    deviceData.brand = getInputValue('android-brand');
                    deviceData.model = getInputValue('android-model');
                    deviceData.imei = getInputValue('android-imei');
                    
                    if (!deviceData.imei) {
                        alert('L\'IMEI est requis pour les appareils Android');
                        return;
                    }
                }
                
                // Save to localStorage avec gestion d'erreur
                let devices = [];
                try {
                    const existing = localStorage.getItem('comsync_devices');
                    if (existing) {
                        devices = JSON.parse(existing);
                    }
                } catch (parseError) {
                    console.warn('Erreur parsing devices:', parseError);
                    devices = [];
                }
                
                devices.push(deviceData);
                localStorage.setItem('comsync_devices', JSON.stringify(devices));
                
                closeAddDeviceModal();
                loadDevices();
                
                alert(`Appareil enregistré avec succès !\n\nID: ${deviceId}\nNom: ${deviceData.name || 'Non nommé'}\n\nL'appareil doit être activé pour apparaître en ligne.`);
                
            } catch (error) {
                console.error('Erreur sauvegarde appareil:', error);
                alert('Erreur lors de l\'enregistrement. Veuillez réessayer.');
            }
        }

        function deleteDevice(deviceId) {
            if (!confirm('Êtes-vous sûr de vouloir supprimer cet appareil ?')) return;
            
            let devices = JSON.parse(localStorage.getItem('comsync_devices') || '[]');
            devices = devices.filter(d => d.id !== deviceId);
            localStorage.setItem('comsync_devices', JSON.stringify(devices));
            
            loadDevices();
        }

        function toggleDeviceStatus(deviceId) {
            let devices = JSON.parse(localStorage.getItem('comsync_devices') || '[]');
            const device = devices.find(d => d.id === deviceId);
            if (device) {
                device.status = device.status === 'online' ? 'offline' : 'online';
                if (device.status === 'online') {
                    device.lastSync = new Date().toLocaleString();
                }
                localStorage.setItem('comsync_devices', JSON.stringify(devices));
                loadDevices();
            }
        }

        function showDeviceDetails(deviceId) {
            const devices = JSON.parse(localStorage.getItem('comsync_devices') || '[]');
            const device = devices.find(d => d.id === deviceId);
            if (!device) return;
            
            const content = `
                <div class="p-6 border-b border-gray-700 flex justify-between items-center">
                    <h2 class="text-xl font-semibold">Détails de l'appareil</h2>
                    <button onclick="closeDeviceDetails()" class="text-gray-400 hover:text-white">
                        <i data-feather="x" class="w-6 h-6"></i>
                    </button>
                </div>
                <div class="p-6">
                    <div class="flex items-center space-x-4 mb-6">
                        <div class="w-16 h-16 bg-blue-600 rounded-xl flex items-center justify-center text-2xl font-bold">
                            ${device.brand ? device.brand.substring(0, 2).toUpperCase() : 'NA'}
                        </div>
                        <div>
                            <h3 class="text-lg font-semibold">${device.name || 'Appareil sans nom'}</h3>
                            <p class="text-gray-400">${device.brand} ${device.model}</p>
                            <span class="status-badge ${device.status === 'online' ? 'status-online' : 'status-offline'} mt-1">
                                ${device.status === 'online' ? 'En ligne' : 'Hors ligne'}
                            </span>
                        </div>
                    </div>
                    
                    <div class="space-y-3 mb-6">
                        <div class="flex justify-between py-2 border-b border-gray-700">
                            <span class="text-gray-400">ID Appareil</span>
                            <span class="font-mono text-sm">${device.id}</span>
                        </div>
                        <div class="flex justify-between py-2 border-b border-gray-700">
                            <span class="text-gray-400">Type</span>
                            <span class="capitalize">${device.type}</span>
                        </div>
                        ${device.imei ? `
                        <div class="flex justify-between py-2 border-b border-gray-700">
                            <span class="text-gray-400">IMEI</span>
                            <span class="font-mono text-sm">${device.imei}</span>
                        </div>` : ''}
                        ${device.frequency ? `
                        <div class="flex justify-between py-2 border-b border-gray-700">
                            <span class="text-gray-400">Fréquence</span>
                            <span>${device.frequency} MHz</span>
                        </div>` : ''}
                        ${device.macAddress ? `
                        <div class="flex justify-between py-2 border-b border-gray-700">
                            <span class="text-gray-400">Adresse MAC</span>
                            <span class="font-mono text-sm">${device.macAddress}</span>
                        </div>` : ''}
                        <div class="flex justify-between py-2 border-b border-gray-700">
                            <span class="text-gray-400">Dernière synchronisation</span>
                            <span>${device.lastSync || 'Jamais'}</span>
                        </div>
                        <div class="flex justify-between py-2 border-b border-gray-700">
                            <span class="text-gray-400">Ajouté le</span>
                            <span>${new Date(device.createdAt).toLocaleDateString()}</span>
                        </div>
                    </div>
                    
                    <div class="flex space-x-3">
                        <button onclick="closeDeviceDetails()" class="flex-1 btn-secondary">Fermer</button>
                        <button onclick="closeDeviceDetails(); deleteDevice('${device.id}')" class="flex-1 bg-red-600 hover:bg-red-700 text-white py-2 rounded-lg">
                            Supprimer
                        </button>
                    </div>
                </div>
            `;
            
            document.getElementById('device-details-content').innerHTML = content;
            document.getElementById('device-details-modal').classList.remove('hidden');
            feather.replace();
        }

        function closeDeviceDetails() {
            document.getElementById('device-details-modal').classList.add('hidden');
        }

        function generateNewQR() {
            alert('Nouveau QR Code généré pour l\'appareil.');
        }

        // ========== IMEI CONNECTION FEATURES ==========
        let imeiHistory = JSON.parse(localStorage.getItem('comsync_imei_history') || '[]');
        let currentImeiSearch = null;

        function formatImeiInput(input) {
            // Only allow digits, max 15
            input.value = input.value.replace(/[^0-9]/g, '').slice(0, 15);
            
            // Auto-search after 15 digits
            if (input.value.length === 15) {
                searchImei();
            }
        }

        function openImeiConnectModal() {
            document.getElementById('imei-connect-modal').classList.remove('hidden');
            document.getElementById('imei-search-input').value = '';
            document.getElementById('imei-validation-status').classList.add('hidden');
            document.getElementById('imei-connected-info').classList.add('hidden');
            document.getElementById('imei-search-results').classList.add('hidden');
            renderImeiHistory();
            setTimeout(() => {
                document.getElementById('imei-search-input').focus();
                if (typeof feather !== 'undefined') feather.replace();
            }, 100);
        }

        function closeImeiConnectModal() {
            document.getElementById('imei-connect-modal').classList.add('hidden');
            currentImeiSearch = null;
        }

        function scanImeiBarcode() {
            // Simulate barcode scan
            const fakeImei = '35' + Array.from({length: 13}, () => Math.floor(Math.random() * 10)).join('');
            document.getElementById('imei-search-input').value = fakeImei;
            searchImei();
        }

        function validateImei(imei) {
            // Luhn algorithm for IMEI validation
            if (!/^[0-9]{15}$/.test(imei)) return false;
            let sum = 0;
            for (let i = 0; i < 14; i++) {
                let d = parseInt(imei[i]);
                if (i % 2 === 1) d *= 2;
                if (d > 9) d -= 9;
                sum += d;
            }
            const checkDigit = (10 - (sum % 10)) % 10;
            return parseInt(imei[14]) === checkDigit;
        }

        function searchImei() {
            const imei = document.getElementById('imei-search-input').value.trim();
            if (!imei || imei.length < 14) {
                alert('Veuillez entrer un numéro IMEI valide (14-15 chiffres)');
                return;
            }

            currentImeiSearch = imei;
            
            // Show validation
            const statusDiv = document.getElementById('imei-validation-status');
            statusDiv.classList.remove('hidden');
            document.getElementById('imei-connected-info').classList.add('hidden');
            document.getElementById('imei-search-results').classList.add('hidden');

            const isValid = validateImei(imei);
            
            // Simulate search delay
            setTimeout(() => {
                const iconDiv = document.getElementById('imei-valid-icon');
                const textEl = document.getElementById('imei-valid-text');
                const subEl = document.getElementById('imei-valid-sub');

                if (isValid) {
                    iconDiv.innerHTML = '<i data-feather="check-circle" class="w-5 h-5 text-green-400"></i>';
                    iconDiv.className = 'w-10 h-10 rounded-full flex items-center justify-center bg-green-900/30';
                    textEl.textContent = 'IMEI Valide';
                    textEl.className = 'font-medium text-green-400';
                    subEl.textContent = 'Numéro IMEI vérifié avec succès';
                } else {
                    iconDiv.innerHTML = '<i data-feather="alert-triangle" class="w-5 h-5 text-yellow-400"></i>';
                    iconDiv.className = 'w-10 h-10 rounded-full flex items-center justify-center bg-yellow-900/30';
                    textEl.textContent = 'IMEI Invalide';
                    textEl.className = 'font-medium text-yellow-400';
                    subEl.textContent = 'Le numéro ne passe pas la vérification Luhn — vérifiez le numéro';
                }
                if (typeof feather !== 'undefined') feather.replace();

                // Search in existing devices
                const devices = JSON.parse(localStorage.getItem('comsync_devices') || '[]');
                const matched = devices.filter(d => d.imei && d.imei.includes(imei));

                if (matched.length > 0) {
                    const resultsDiv = document.getElementById('imei-search-results');
                    const resultsList = document.getElementById('imei-results-list');
                    resultsDiv.classList.remove('hidden');
                    
                    resultsList.innerHTML = matched.map(d => `
                        <div class="flex items-center justify-between p-3 bg-gray-700/30 rounded-lg hover:bg-gray-700/50 cursor-pointer transition-colors" onclick="selectImeiDevice('${d.id}')">
                            <div class="flex items-center gap-3">
                                <div class="w-8 h-8 rounded-lg ${d.status === 'online' ? 'bg-green-600' : 'bg-gray-600'} flex items-center justify-center">
                                    <i data-feather="${d.type === 'radio' ? 'radio' : 'smartphone'}" class="w-4 h-4 text-white"></i>
                                </div>
                                <div>
                                    <p class="text-sm font-medium">${d.name || d.brand + ' ' + d.model}</p>
                                    <p class="text-xs text-gray-400 font-mono">IMEI: ${d.imei}</p>
                                </div>
                            </div>
                            <span class="text-xs px-2 py-1 rounded-full ${d.status === 'online' ? 'bg-green-900/30 text-green-400' : 'bg-gray-700 text-gray-400'}">${d.status === 'online' ? 'En ligne' : 'Hors ligne'}</span>
                        </div>
                    `).join('');
                    if (typeof feather !== 'undefined') feather.replace();
                }
            }, 800);
        }

        function selectImeiDevice(deviceId) {
            const devices = JSON.parse(localStorage.getItem('comsync_devices') || '[]');
            const device = devices.find(d => d.id === deviceId);
            if (!device) return;

            // Show connected info
            document.getElementById('imei-connected-info').classList.remove('hidden');
            document.getElementById('imei-device-name').textContent = device.name || (device.brand + ' ' + device.model);
            document.getElementById('imei-device-imei').textContent = device.imei || 'N/A';
            document.getElementById('imei-device-brand').textContent = (device.brand || '—') + ' ' + (device.model || '');
            document.getElementById('imei-device-status').textContent = device.status === 'online' ? 'En ligne' : 'Hors ligne';
            document.getElementById('imei-device-status').className = device.status === 'online' ? 'text-green-400' : 'text-gray-400';
            document.getElementById('imei-device-lastseen').textContent = device.lastSync || 'Jamais';
            document.getElementById('imei-search-results').classList.add('hidden');

            // Set device online if offline
            if (device.status !== 'online') {
                device.status = 'online';
                device.lastSync = new Date().toLocaleString();
                localStorage.setItem('comsync_devices', JSON.stringify(devices));
            }

            // Add to IMEI history
            addToImeiHistory(device.imei, device.name || device.brand);

            if (typeof feather !== 'undefined') feather.replace();
        }

        function connectByImei() {
            const imei = document.getElementById('imei-search-input').value.trim();
            if (!imei || imei.length < 14) {
                alert('Veuillez entrer un numéro IMEI avant de vous connecter');
                return;
            }

            // Search in existing devices first
            const devices = JSON.parse(localStorage.getItem('comsync_devices') || '[]');
            const existing = devices.find(d => d.imei === imei);
            
            if (existing) {
                selectImeiDevice(existing.id);
                loadDevices();
                return;
            }

            // If not found, create new device from IMEI
            const deviceId = 'DEV-IMEI-' + Date.now().toString(36).toUpperCase();
            const newDevice = {
                id: deviceId,
                type: 'android',
                name: 'Appareil IMEI ' + imei.slice(-4),
                brand: 'Inconnu',
                model: 'Détecté par IMEI',
                imei: imei,
                status: 'online',
                lastSync: new Date().toLocaleString(),
                companyId: (companyData && companyData.id) ? companyData.id : 'DEMO-001',
                createdAt: new Date().toISOString()
            };

            devices.push(newDevice);
            localStorage.setItem('comsync_devices', JSON.stringify(devices));

            // Show connected info
            document.getElementById('imei-connected-info').classList.remove('hidden');
            document.getElementById('imei-search-results').classList.add('hidden');
            document.getElementById('imei-device-name').textContent = newDevice.name;
            document.getElementById('imei-device-imei').textContent = newDevice.imei;
            document.getElementById('imei-device-brand').textContent = newDevice.brand + ' ' + newDevice.model;
            document.getElementById('imei-device-status').textContent = 'En ligne';
            document.getElementById('imei-device-status').className = 'text-green-400';
            document.getElementById('imei-device-lastseen').textContent = newDevice.lastSync;

            // Add to history
            addToImeiHistory(imei, newDevice.name);

            loadDevices();

            if (typeof feather !== 'undefined') feather.replace();
        }

        function addToImeiHistory(imei, name) {
            // Remove duplicate
            imeiHistory = imeiHistory.filter(h => h.imei !== imei);
            imeiHistory.unshift({ imei, name, timestamp: new Date().toISOString() });
            // Keep max 5
            imeiHistory = imeiHistory.slice(0, 5);
            localStorage.setItem('comsync_imei_history', JSON.stringify(imeiHistory));
            renderImeiHistory();
        }

        function renderImeiHistory() {
            const container = document.getElementById('imei-history');
            if (!container) return;

            if (imeiHistory.length === 0) {
                container.innerHTML = '<span class="text-xs text-gray-600">Aucun IMEI récent</span>';
                return;
            }

            container.innerHTML = imeiHistory.map(h => `
                <button onclick="document.getElementById('imei-search-input').value='${h.imei}'; searchImei();" class="flex items-center gap-2 px-3 py-1.5 bg-gray-700/50 rounded-lg hover:bg-gray-700 transition-colors text-xs group">
                    <i data-feather="smartphone" class="w-3 h-3 text-green-400"></i>
                    <span class="font-mono text-gray-300">${h.imei}</span>
                    <span class="text-gray-500">${h.name || ''}</span>
                    <i data-feather="x" class="w-3 h-3 text-gray-600 group-hover:text-red-400 transition-colors" onclick="event.stopPropagation(); removeImeiHistory('${h.imei}')"></i>
                </button>
            `).join('');

            if (typeof feather !== 'undefined') feather.replace();
        }

        function removeImeiHistory(imei) {
            imeiHistory = imeiHistory.filter(h => h.imei !== imei);
            localStorage.setItem('comsync_imei_history', JSON.stringify(imeiHistory));
            renderImeiHistory();
        }

        // Simulate real-time updates avec gestion d'erreur
        setInterval(() => {
            try {
                const devices = JSON.parse(localStorage.getItem('comsync_devices') || '[]');
                if (!Array.isArray(devices)) return;
                
                let updated = false;
                
                devices.forEach(device => {
                    if (device && device.status === 'online' && Math.random() > 0.95) {
                        device.lastSync = new Date().toLocaleString();
                        updated = true;
                    }
                });
                
                if (updated) {
                    localStorage.setItem('comsync_devices', JSON.stringify(devices));
                    loadDevices();
                }
            } catch (e) {
                console.warn('Erreur mise à jour temps réel:', e);
            }
        }, 5000);

        // Initialize
        loadCompanyData();

        // Handle browser navigation
        window.addEventListener('popstate', function(event) {
            location.reload();
        });
        history.pushState(null, null, location.href);
    </script>
</body>
</html>