File size: 53,930 Bytes
0e35c8a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8de08fe
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
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>نظام المقارنة والترجمة - شركة الريحان للترجمة</title>
  <!-- استيراد مكتبات Tailwind وFont Awesome وMammoth -->
  <link href="https://cdnjs.cloudflare.com/ajax/libs/tailwindcss/2.2.19/tailwind.min.css" rel="stylesheet">
  <script src="https://cdnjs.cloudflare.com/ajax/libs/mammoth/1.6.0/mammoth.browser.min.js"></script>
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">
  <style>
    /* ================================
       تنسيقات الحركات والتأثيرات
    ================================= */
    @keyframes gradient {
      0% { background-position: 0% 50%; }
      50% { background-position: 100% 50%; }
      100% { background-position: 0% 50%; }
    }
    .animate-gradient {
      background-size: 200% 200%;
      animation: gradient 15s ease infinite;
    }
    .transition-all { transition: all 0.3s ease-in-out; }
    .animate-scale { transition: transform 0.2s ease-in-out; }
    .animate-scale:hover { transform: scale(1.02); }
    .pulse-animation { animation: pulse 2s infinite; }
    @keyframes pulse {
      0% { box-shadow: 0 0 0 0 rgba(156,39,176,0.4); }
      70% { box-shadow: 0 0 0 10px rgba(156,39,176,0); }
      100% { box-shadow: 0 0 0 0 rgba(156,39,176,0); }
    }

    /* ================================
       تنسيقات النصوص والتحديد
    ================================= */
    .text-comparison { line-height: 1.8; white-space: pre-wrap; }
    .highlight-number {
      background-color: #FDE68A;
      padding: 0 4px;
      border-radius: 3px;
      font-weight: bold;
    }
    .highlight-missing {
      background-color: #BFDBFE;
      padding: 0 4px;
      border-radius: 3px;
      font-style: italic;
    }
    .highlight-meaning {
      background-color: #fecaca;
      color: #B91C1C;
      padding: 0 4px;
      border-radius: 3px;
      font-weight: bold;
    }

    /* ================================
       تنسيق عرض السطور في المعاينة
    ================================= */
    .split-view {
      display: grid;
      grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
      gap: 1rem;
    }
    .line-item {
      display: flex;
      align-items: flex-start;
      margin-bottom: 0.5rem;
    }
    .line-number {
      width: 30px;
      font-weight: bold;
      color: #4B5563;
      flex-shrink: 0;
    }
    .line-text { flex: 1; }

    /* ================================
       تحسين تنسيق البطاقات والعناصر
    ================================= */
    .card-hover {
      transition: all 0.3s ease;
    }
    .card-hover:hover {
      box-shadow: 0 10px 25px -5px rgba(156,39,176,0.1), 0 10px 10px -5px rgba(156,39,176,0.04);
      transform: translateY(-2px);
    }

    /* ================================
       تنسيقات المسودة المخفية والتقسيمات
    ================================= */
    .collapsible-section {
      border: 1px solid #e5e7eb;
      border-radius: 8px;
      margin-bottom: 8px;
      overflow: hidden;
      background-color: #f9fafb;
    }
    
    .section-header {
      background-color: #f3f4f6;
      padding: 12px 16px;
      cursor: pointer;
      display: flex;
      justify-content: space-between;
      align-items: center;
      font-weight: 600;
      border-bottom: 1px solid #e5e7eb;
    }
    
    .section-header:hover {
      background-color: #e5e7eb;
    }
    
    .section-content {
      max-height: 0;
      overflow: hidden;
      transition: max-height 0.3s ease-out;
      padding: 0 16px;
    }
    
    .section-content.open {
      max-height: 1000px; /* تغييره حسب احتياجك */
      padding: 16px;
      transition: max-height 0.5s ease-in, padding 0.3s ease-in;
    }
    
    .draft-marker {
      display: inline-block;
      background-color: #e5e7eb;
      padding: 2px 6px;
      border-radius: 4px;
      font-size: 0.75rem;
      margin-right: 8px;
      color: #4b5563;
    }
    
    .sync-word {
      color: #4f46e5;
      font-weight: 500;
    }
    
    .paragraph-section {
      border-left: 3px solid #d1d5db;
      padding-left: 12px;
      margin-bottom: 16px;
    }

    /* ================================
       تنسيقات جديدة للشعار والعرض المحسن
    ================================= */
    .logo-container {
      display: flex;
      align-items: center;
      justify-content: center;
      margin-bottom: 1rem;
    }
    
    .logo {
      width: 80px;
      height: 80px;
      border-radius: 50%;
      background-color: #fff;
      display: flex;
      align-items: center;
      justify-content: center;
      box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
      margin-left: 1rem;
      overflow: hidden;
    }
    
    .company-name {
      font-size: 1.5rem;
      font-weight: bold;
      color: #fff;
      text-shadow: 1px 1px 2px rgba(0, 0, 0, 0.2);
    }
    
    /* طريقة العرض الجديدة للنصوص المقسمة */
    .segment-comparison {
      border: 1px solid #e5e7eb;
      border-radius: 8px;
      margin-bottom: 1rem;
      overflow: hidden;
    }
    
    .segment-header {
      background-color: #f3f4f6;
      padding: 0.75rem 1rem;
      font-weight: 600;
      border-bottom: 1px solid #e5e7eb;
      display: flex;
      justify-content: space-between;
    }
    
    .segment-content {
      display: grid;
      grid-template-columns: 1fr 1fr;
      gap: 1px;
      background-color: #e5e7eb;
    }
    
    .segment-source, .segment-target {
      background-color: #fff;
      padding: 1rem;
    }
    
    .segment-source {
      background-color: #f0f9ff;
    }
    
    .segment-target {
      background-color: #fdf2f8;
    }
    
    .segment-notes {
      grid-column: span 2;
      background-color: #fffbeb;
      padding: 0.75rem 1rem;
      border-top: 1px solid #e5e7eb;
      font-size: 0.9rem;
    }
    
    .segment-tag {
      display: inline-block;
      padding: 0.25rem 0.5rem;
      border-radius: 9999px;
      font-size: 0.75rem;
      font-weight: 500;
      margin-right: 0.5rem;
    }
    
    .tag-error {
      background-color: #fee2e2;
      color: #b91c1c;
    }
    
    .tag-warning {
      background-color: #fef3c7;
      color: #92400e;
    }
    
    .tag-info {
      background-color: #dbeafe;
      color: #1e40af;
    }
    
    .view-tabs {
      display: flex;
      border-bottom: 1px solid #e5e7eb;
      margin-bottom: 1rem;
    }
    
    .view-tab {
      padding: 0.75rem 1.5rem;
      cursor: pointer;
      border-bottom: 2px solid transparent;
      font-weight: 500;
    }
    
    .view-tab.active {
      border-bottom-color: #6366f1;
      color: #4f46e5;
    }
    
    .view-content {
      display: none;
    }
    
    .view-content.active {
      display: block;
    }
  </style>
</head>
<body class="bg-gradient-to-br from-gray-100 via-blue-100 to-indigo-100 min-h-screen">
  <div class="min-h-screen pb-12">
    <!-- ============ رأس الصفحة ============ -->
    <header class="bg-gradient-to-r from-indigo-700 via-purple-700 to-pink-700 animate-gradient text-white py-10 mb-10 shadow-xl">
        <div class="max-w-6xl mx-auto px-4">
          <!-- شعار واسم الشركة -->
          <div class="flex items-center justify-center mb-6">
            <div class="logo-container flex items-center">
              <div class="logo mr-4">
                <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100" width="48" height="48">
                  <image xlink:href="https://ufastpro.com/wp-content/uploads/2025/04/471276448_1153582006774617_1534220249669349002_n.jpg" width="100" height="100"/>
                </svg>
              </div>
              <div class="company-name text-2xl font-bold">شركة الريحان للترجمة</div>
            </div>
          </div>
          <h1 class="text-5xl font-bold text-center mb-4 animate-scale">النظام المراجع الذكي</h1>
          <p class="text-center text-xl text-blue-100 opacity-90">مقارنة وتحليل النصوص – المصدر مرجع أساسي</p>
        </div>
      </header>

    <!-- ============ شرح البرنامج التعريفي ============ -->
    <section id="programExplanation" class="max-w-6xl mx-auto px-4 mb-8">
      <div class="bg-white rounded-2xl shadow-lg p-8 border border-gray-100">
        <p class="text-lg text-gray-800">
          هذا البرنامج مصمم لمقارنة النصوص التقنية وتحليلها بدقة عالية، مع تحديد الاختلافات في الأرقام، النصوص المفقودة واختلافات المعنى. يمكنك أيضًا التحقق مما إذا تم استخدام قاعدة المصطلحات أثناء التحليل وتنزيل تقرير مفصل بصيغة إكسيل أو وورد.
        </p>
      </div>
    </section>

    <!-- ============ المحتوى الرئيسي ============ -->
    <main class="max-w-6xl mx-auto px-4">
      <!-- قسم رفع الملفات -->
      <div class="bg-white rounded-2xl shadow-lg p-8 border border-gray-100 hover:shadow-xl transition-all animate-scale mb-8 card-hover">
        <h2 class="text-2xl font-bold mb-6 text-gray-800 flex items-center border-b pb-3">
          <i class="fas fa-file-upload text-indigo-600 ml-2"></i> تحميل الملفات
        </h2>
        <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
          <!-- ملف السورس -->
          <div class="group border-2 border-dashed border-indigo-300 rounded-xl p-8 text-center hover:border-indigo-500 transition-colors duration-300 bg-indigo-50 hover:bg-indigo-100">
            <label class="cursor-pointer block">
              <input type="file" id="sourceFile" accept=".docx,.pdf" class="hidden">
              <i class="fas fa-file-upload text-5xl text-indigo-500 mb-4"></i>
              <span class="text-lg text-indigo-600 group-hover:text-indigo-700">ملف السورس</span>
            </label>
          </div>
          <!-- ملف التارجت -->
          <div class="group border-2 border-dashed border-pink-300 rounded-xl p-8 text-center hover:border-pink-500 transition-colors duration-300 bg-pink-50 hover:bg-pink-100">
            <label class="cursor-pointer block">
              <input type="file" id="targetFile" accept=".docx,.pdf" class="hidden">
              <i class="fas fa-file-download text-5xl text-pink-500 mb-4"></i>
              <span class="text-lg text-pink-600 group-hover:text-pink-700">ملف التارجت</span>
            </label>
          </div>
        </div>
        <div id="processStatus" class="hidden mt-4">
          <div class="flex items-center justify-center space-x-3 bg-indigo-100 rounded-xl p-4">
            <div class="animate-spin h-8 w-8 border-4 border-indigo-600 rounded-full border-t-transparent"></div>
            <span class="text-lg text-indigo-700">جارٍ معالجة الملف...</span>
          </div>
        </div>
      </div>

      <!-- قسم إدخال النصوص يدويًا وخيار استخدام قاعدة المصطلحات -->
      <div class="bg-white rounded-2xl shadow-lg p-8 border border-gray-100 hover:shadow-xl transition-all animate-scale mb-8 card-hover">
        <div class="space-y-6">
          <!-- النص المصدر -->
          <div class="group">
            <label class="block text-lg font-bold text-gray-700 mb-3 flex items-center">
              <i class="fas fa-language text-indigo-600 ml-2"></i> النص المصدر
            </label>
            <textarea id="sourceText" dir="rtl" class="w-full px-6 py-4 border-2 border-gray-200 rounded-xl focus:ring-indigo-200 focus:border-indigo-400 transition-all resize-none text-lg" rows="6" placeholder="اكتب النص المصدر هنا..."></textarea>
          </div>
          <!-- النص الهدف -->
          <div class="group">
            <label class="block text-lg font-bold text-gray-700 mb-3 flex items-center">
              <i class="fas fa-language text-pink-600 ml-2"></i> النص الهدف
            </label>
            <textarea id="targetText" dir="ltr" class="w-full px-6 py-4 border-2 border-gray-200 rounded-xl focus:ring-pink-200 focus:border-pink-400 transition-all resize-none text-lg" rows="6" placeholder="اكتب النص الهدف هنا..."></textarea>
          </div>
          <!-- خيار استخدام قاعدة المصطلحات -->
          <div class="mt-4 flex items-center">
            <input type="checkbox" id="terminologyCheck" class="mr-2">
            <label for="terminologyCheck" class="text-lg text-gray-700">استخدام قاعدة المصطلحات</label>
          </div>
        </div>
      </div>

      <!-- قسم المصادر الإضافية -->
      <div class="bg-white rounded-2xl shadow-lg p-8 border border-gray-100 hover:shadow-xl transition-all animate-scale mb-8 card-hover">
        <h2 class="text-2xl font-bold mb-6 text-gray-800 flex items-center border-b pb-3">
          <i class="fas fa-book-open text-green-600 ml-2"></i> مصادر إضافية
        </h2>
        <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
          <!-- رفع ملف المصادر الإضافية -->
          <div class="group border-2 border-dashed border-green-300 rounded-xl p-8 text-center hover:border-green-500 transition-colors duration-300 bg-green-50 hover:bg-green-100">
            <label class="cursor-pointer block">
              <input type="file" id="sourceExtraFile" accept=".docx,.pdf" class="hidden">
              <i class="fas fa-upload text-5xl text-green-500 mb-4"></i>
              <span class="text-lg text-green-600 group-hover:text-green-700">تحميل ملف المصدر</span>
            </label>
          </div>
          <!-- إدخال المصادر يدويًا -->
          <div class="group">
            <label class="block text-lg font-bold text-gray-700 mb-3 flex items-center">
              <i class="fas fa-edit text-green-600 ml-2"></i> إدخال المصادر يدويًا
            </label>
            <textarea id="sourceExtraText" dir="rtl" class="w-full px-6 py-4 border-2 border-green-200 rounded-xl focus:ring-green-200 focus:border-green-400 transition-all resize-none text-lg" rows="6" placeholder="اكتب المصادر هنا..."></textarea>
          </div>
        </div>
      </div>

      <!-- زر التحليل -->
      <button id="submitBtn" class="w-full bg-gradient-to-r from-indigo-600 to-pink-600 hover:from-indigo-700 hover:to-pink-700 text-white font-bold py-5 px-8 rounded-xl transition-all transform hover:scale-105 focus:ring-indigo-200 text-xl shadow-lg hover:shadow-xl mb-8 pulse-animation">
        <div class="flex items-center justify-center">
          <i class="fas fa-sync-alt ml-2"></i> تحليل النصوص
        </div>
      </button>

      <!-- شاشة عرض نتائج التحليل مع علامات التبويب للطرق المختلفة -->
      <div id="resultSection" class="bg-white rounded-2xl shadow-lg p-8 border border-gray-100 hover:shadow-xl transition-all animate-scale mb-8 hidden card-hover">
        <h2 class="text-2xl font-bold mb-6 text-gray-800 border-b pb-3 flex items-center">
          <i class="fas fa-search text-green-600 ml-2"></i> نتائج التحليل والمقارنة
        </h2>
        <div id="errorsList" class="space-y-3 mb-6"></div>
        
        <!-- علامات التبويب للطرق المختلفة -->
        <div class="view-tabs">
          <div class="view-tab active" data-tab="classic-view">طريقة العرض الكلاسيكية</div>
          <div class="view-tab" data-tab="segment-view">طريقة العرض المقسمة</div>
        </div>
        
        <!-- محتوى طريقة العرض الكلاسيكية -->
        <div id="classic-view" class="view-content active">
          <div class="result-section split-view">
            <!-- عرض النص المصدر بعد التحديد مع ترقيم السطور -->
            <div>
              <h4 class="text-lg font-bold text-gray-700 mb-3 flex items-center">
                <i class="fas fa-file-alt text-indigo-600 ml-2"></i> النص المصدر (مع التعليم)
              </h4>
              <div id="sourceTextReview" class="bg-indigo-50 rounded-xl p-6 min-h-[200px] border-2 border-indigo-100 text-comparison"></div>
            </div>
            <!-- عرض النص الهدف بعد التحديد مع ترقيم السطور -->
            <div>
              <h4 class="text-lg font-bold text-gray-700 mb-3 flex items-center">
                <i class="fas fa-file-alt text-pink-600 ml-2"></i> النص الهدف (مع التعليم)
              </h4>
              <div id="targetTextReview" class="bg-gray-50 rounded-xl p-6 min-h-[200px] border-2 border-gray-200 text-comparison"></div>
            </div>
          </div>
        </div>
        
        <!-- محتوى طريقة العرض المقسمة -->
        <div id="segment-view" class="view-content">
          <div id="segmentedComparisonContainer" class="space-y-4">
            <!-- سيتم إنشاء المقاطع هنا بواسطة JavaScript -->
          </div>
        </div>
      </div>

      <!-- صندوق عرض الشرح التفصيلي للنتائج -->
      <div id="explanationBox" class="bg-white rounded-2xl shadow-lg p-8 border border-gray-100 hover:shadow-xl transition-all animate-scale mb-8 hidden card-hover">
        <h2 class="text-2xl font-bold mb-6 text-gray-800 border-b pb-3 flex items-center">
          <i class="fas fa-info-circle text-green-600 ml-2"></i> شرح الاختلافات
        </h2>
        <div id="explanationText" class="text-lg text-gray-700"></div>
      </div>

      <!-- قسم المسودة (تقسيمات الفقرات) - محسن ومخفي بشكل افتراضي -->
      <div id="fullTextDraftSection" class="bg-white rounded-2xl shadow-lg p-8 border border-gray-100 transition-all animate-scale mb-8 hidden card-hover">
        <h2 class="text-2xl font-bold mb-6 text-gray-800 border-b pb-3 flex items-center">
          <i class="fas fa-file-alt text-blue-600 ml-2"></i> مسودة التحليل النصي الكامل
          <span class="draft-marker mr-2">مسودة</span>
        </h2>
        <div id="paragraphDivisionsContainer" class="mt-4 space-y-2">
          <!-- سيتم إنشاء التقسيمات هنا بواسطة JavaScript -->
        </div>
      </div>
      
      <div class="flex flex-col md:flex-row md:items-center md:justify-between mb-8 space-y-4 md:space-y-0">
        <button id="toggleDraftBtn" class="w-full md:w-auto bg-blue-600 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded">
          عرض/إخفاء مسودة التحليل
        </button>
        <!-- أزرار تنزيل التقرير -->
        <div class="flex space-x-4">
          <button id="downloadExcelBtn" class="w-full md:w-auto bg-green-600 hover:bg-green-700 text-white font-bold py-2 px-4 rounded">
            تنزيل التقرير (Excel)
          </button>
          <button id="downloadWordBtn" class="w-full md:w-auto bg-purple-600 hover:bg-purple-700 text-white font-bold py-2 px-4 rounded">
            تنزيل التقرير (Word)
          </button>
        </div>
      </div>
    </main>
  </div>

  <!-- ================================
       جافا سكريبت: الوظائف والمعالجة
  ================================= -->
  <script>
    // إعدادات API
    const DEEPSEEK_API_URL = 'https://api.deepseek.com/chat/completions';
    const DEEPSEEK_API_KEY = 'sk-15606736ed9e4aea8b7cc11a195d2b01';

    // إعدادات API ChatGPT-4o
    const CHATGPT_API_URL = 'https://api.openai.com/v1/chat/completions';
    const CHATGPT_API_KEY = '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';

    let fullAnalysisText = ''; // متغير لتخزين النص الكامل للتحليل
    let analysisSegments = []; // متغير لتخزين مقاطع التحليل المقسمة

    /* 
       البرومبت الجديد: يتم فيه تحديد أن النصوص مليئة بالأخطاء والنواقص،
       مع ضرورة الحفاظ على علامات التحديد (التعليم) كما هي.
    */
    const ANALYSIS_PROMPT = `أنت خبير لغوي متخصص في مراجعة الترجمة التقنية. مهمتك مقارنة النص المصدر والنص الهدف بدقة عالية مع العلم أن النصوص مليانة بالأخطاء والنواقص.
لا تقم بإزالة أو تعديل العلامات التالية:
• الأرقام: تحافظ على علامات < و >.
• النصوص المفقودة: تحافظ على علامات __ و __.
• اختلافات المعنى: تحافظ على علامات [MEANING] و [/MEANING].

اعتمد النص المصدر كأساس للمقارنة، وقم بتحديد:
1. اختلافات الأرقام باستخدام <الرقم_في_المصدر> → <الرقم_في_الهدف>.
2. النصوص المفقودة كما هي بين علامتي __.
3. اختلافات المعنى باستخدام [MEANING] مع الحفاظ على التعليم.

النص المصدر:
{source}

النص الهدف:
{target}`;

    // برومبت لتقسيم النص باستخدام ChatGPT-4o
    const TEXT_DIVISION_PROMPT = `قم بتقسيم النص التالي إلى أجزاء منطقية للتحليل.
    يجب أن يكون كل جزء وحدة متماسكة (فقرة، قسم، إلخ) لا تتجاوز 500 كلمة.
    أعد النص كمصفوفة JSON بالأجزاء. الصيغة: {"segments": ["جزء1", "جزء2", ...]}

    النص للتقسيم:
    {text}`;
    
    // برومبت لإيجاد الكلمة الأخيرة المشتركة للتزامن
    const SYNC_WORD_PROMPT = `قم بتحليل النص التالي وإيجاد آخر كلمة أو جملة قصيرة (لا تزيد عن 3 كلمات) مناسبة ليمكن استخدامها كنقطة تزامن بين الفقرات. اختر كلمة أو جملة تظهر بشكل طبيعي في النص وتكون مناسبة للتقسيم.
    أعِد فقط الكلمة أو الجملة المحددة دون أي إضافات أخرى.

    النص:
    {text}`;

    /* =====================================
       دالة لتقسيم النص باستخدام ChatGPT-4o
    ===================================== */
    async function divideTextWithChatGPT(text) {
      try {
        // إذا كان النص قصيرًا، لا داعي لتقسيمه
        if (countWords(text) <= 500) {
          return [text];
        }
    
        // تحضير البيانات لـ ChatGPT-4o
        const prompt = TEXT_DIVISION_PROMPT.replace("{text}", text);
        const payload = {
          model: "gpt-4o",
          messages: [
            { role: "system", content: "أنت مساعد متخصص في تقسيم النصوص إلى أجزاء منطقية." },
            { role: "user", content: prompt }
          ],
          temperature: 0.3,
          max_tokens: 1024
        };
    
        // استدعاء API ChatGPT
        const response = await fetch(CHATGPT_API_URL, {
          method: 'POST',
          headers: {
            'Authorization': 'Bearer ' + CHATGPT_API_KEY,
            'Content-Type': 'application/json'
          },
          body: JSON.stringify(payload)
        });
    
        if (!response.ok) {
          throw new Error('خطأ في API ChatGPT: ' + response.statusText);
        }
    
        const data = await response.json();
        const content = data.choices[0].message.content.trim();
    
        // محاولة تحليل الاستجابة كـ JSON
        try {
          const jsonResponse = JSON.parse(content);
          if (jsonResponse.segments && Array.isArray(jsonResponse.segments)) {
            return jsonResponse.segments;
          }
        } catch (e) {
          // إذا تعذر تحليلها كـ JSON، حاول استخراج الأجزاء يدويًا
          const segments = content.split(/\n{2,}/).filter(seg => seg.trim().length > 0);
          if (segments.length > 0) {
            return segments;
          }
        }
    
        // إذا فشل كل شيء، قسم النص إلى فقرات
        return text.split(/\n{2,}/).filter(para => para.trim().length > 0);
    
      } catch (error) {
        console.error('خطأ في تقسيم النص باستخدام ChatGPT:', error);
        // الخطة البديلة: تقسيم حسب الفقرات
        return text.split(/\n{2,}/).filter(para => para.trim().length > 0);
      }
    }

    /* =====================================
       دالة لإيجاد الكلمة المتزامنة في نهاية كل فقرة
    ===================================== */
    async function findSyncWord(text) {
      try {
        // تحضير البيانات لـ ChatGPT-4o
        const prompt = SYNC_WORD_PROMPT.replace("{text}", text);
        const payload = {
          model: "gpt-4o",
          messages: [
            { role: "system", content: "أنت مساعد متخصص في تحليل النصوص وإيجاد نقاط تزامن مناسبة." },
            { role: "user", content: prompt }
          ],
          temperature: 0.3,
          max_tokens: 50
        };
    
        // استدعاء API ChatGPT
        const response = await fetch(CHATGPT_API_URL, {
          method: 'POST',
          headers: {
            'Authorization': 'Bearer ' + CHATGPT_API_KEY,
            'Content-Type': 'application/json'
          },
          body: JSON.stringify(payload)
        });
    
        if (!response.ok) {
          throw new Error('خطأ في API ChatGPT: ' + response.statusText);
        }
    
        const data = await response.json();
        const syncWord = data.choices[0].message.content.trim();
        
        return syncWord;
      } catch (error) {
        console.error('خطأ في إيجاد الكلمة المتزامنة:', error);
        // في حالة الفشل، نعيد كلمة افتراضية
        return "نهاية الفقرة";
      }
    }

    /* =====================================
       دالة لتحليل الأجزاء باستخدام DeepSeek ودمج النتائج
    ===================================== */
    async function analyzeTextSegments(sourceSegments, targetSegments) {
      // التحقق من أن لدينا نفس عدد الأجزاء
      if (sourceSegments.length !== targetSegments.length) {
        throw new Error('عدد أجزاء المصدر والهدف غير متطابق');
      }
  
      let combinedAnalysis = '';
      const progressDiv = document.createElement('div');
      progressDiv.className = "bg-indigo-100 p-4 rounded-xl mb-4";
      progressDiv.innerHTML = `<div class="flex items-center justify-between">
                                 <div class="flex items-center">
                                   <div class="animate-spin h-6 w-6 border-4 border-indigo-600 rounded-full border-t-transparent ml-3"></div>
                                   <span>جارٍ التحليل...</span>
                                 </div>
                                 <span id="segmentProgress">0/${sourceSegments.length}</span>
                               </div>`;
      document.getElementById('errorsList').appendChild(progressDiv);
      
      // تخزين مقاطع التحليل المنفصلة
      analysisSegments = [];

      // تحليل كل زوج من الأجزاء
      for (let i = 0; i < sourceSegments.length; i++) {
        // تحديث التقدم
        document.getElementById('segmentProgress').textContent = `${i+1}/${sourceSegments.length}`;
    
        // بناء البرومبت لهذا الجزء
        const prompt = ANALYSIS_PROMPT
                        .replace("{source}", sourceSegments[i])
                        .replace("{target}", targetSegments[i]);
    
        // استدعاء DeepSeek API
        const payload = {
          model: "deepseek-reasoner",
          messages: [
            { role: "system", content: "أنت خبير في تحليل النصوص ومقارنتها بدقة عالية." },
            { role: "user", content: prompt }
          ],
          temperature: 0.3,
          max_tokens: 2048,
          stream: false
        };
    
        const response = await fetch(DEEPSEEK_API_URL, {
          method: 'POST',
          headers: {
            'Authorization': 'Bearer ' + DEEPSEEK_API_KEY,
            'Content-Type': 'application/json'
          },
          body: JSON.stringify(payload)
        });
    
        if (!response.ok) {
          throw new Error('حدث خطأ بالشبكة: ' + response.statusText);
        }
    
        const data = await response.json();
        const segmentAnalysis = data.choices[0].message.content.trim();
        
        // أضف هذا المقطع إلى المصفوفة
        analysisSegments.push({
          source: sourceSegments[i],
          target: targetSegments[i],
          analysis: segmentAnalysis
        });
    
        // دمج مع التحليل السابق
        if (i > 0) combinedAnalysis += '\n\n---\n\n';
        combinedAnalysis += `[الجزء ${i+1}]\n${segmentAnalysis}`;
      }
  
      progressDiv.remove();
      return combinedAnalysis;
    }

    /* =====================================
       دالة لعرض التقسيمات كمسودة قابلة للطي
    ===================================== */
    async function displayDraftSections() {
      const container = document.getElementById('paragraphDivisionsContainer');
      container.innerHTML = ''; // مسح المحتوى الحالي

      // إنشاء قسم لكل مقطع تحليل
      for (let i = 0; i < analysisSegments.length; i++) {
        const segment = analysisSegments[i];
        
        // البحث عن كلمة متزامنة في نهاية المقطع
        const syncWord = await findSyncWord(segment.source);
        
        // إنشاء عنصر القسم القابل للطي
        const sectionDiv = document.createElement('div');
        sectionDiv.className = 'collapsible-section';
        
        // إنشاء الترويسة
        const headerDiv = document.createElement('div');
        headerDiv.className = 'section-header';
        headerDiv.innerHTML = `
          <div class="flex items-center">
            <span class="draft-marker">مسودة</span>
            <span>القسم ${i+1}: ${truncateText(segment.source, 50)}</span>
          </div>
          <i class="fas fa-chevron-down"></i>
        `;
        
        // إنشاء محتوى القسم
        const contentDiv = document.createElement('div');
        contentDiv.className = 'section-content';
        
        // تحديد النص المصدر مع تمييز الكلمة المتزامنة في النهاية
        const sourceWithSync = highlightSyncWord(segment.source, syncWord);
        // تحديد النص الهدف مع تمييز الكلمة المتزامنة في النهاية إن وجدت
        const targetWithSync = highlightSyncWord(segment.target, syncWord);
        
        contentDiv.innerHTML = `
          <div class="paragraph-section mb-4">
            <h4 class="font-bold text-gray-700 mb-2">النص المصدر:</h4>
            <div class="bg-indigo-50 p-3 rounded-lg">${sourceWithSync}</div>
          </div>
          <div class="paragraph-section mb-4">
            <h4 class="font-bold text-gray-700 mb-2">النص الهدف:</h4>
            <div class="bg-pink-50 p-3 rounded-lg">${targetWithSync}</div>
          </div>
          <div class="paragraph-section">
            <h4 class="font-bold text-gray-700 mb-2">التحليل:</h4>
            <div class="bg-gray-50 p-3 rounded-lg">${formatAnalysisText(segment.analysis)}</div>
          </div>
        `;
        
        // إضافة الأقسام إلى الحاوية
        sectionDiv.appendChild(headerDiv);
        sectionDiv.appendChild(contentDiv);
        container.appendChild(sectionDiv);
        
        // إضافة مستمع الحدث للنقر على الترويسة
        headerDiv.addEventListener('click', function() {
          contentDiv.classList.toggle('open');
          const icon = headerDiv.querySelector('i.fas');
          icon.classList.toggle('fa-chevron-down');
          icon.classList.toggle('fa-chevron-up');
        });
      }
    }

    /* =====================================
       دالة لعرض المقاطع في طريقة العرض المقسمة
    ===================================== */
    function displaySegmentedView() {
      const container = document.getElementById('segmentedComparisonContainer');
      container.innerHTML = ''; // مسح المحتوى الحالي
      
      // إذا لم تكن هناك مقاطع، أظهر رسالة
      if (!analysisSegments || analysisSegments.length === 0) {
        container.innerHTML = '<div class="p-4 bg-yellow-50 rounded-lg text-center">لم يتم تحليل أي مقاطع بعد. قم بتحليل النصوص أولاً.</div>';
        return;
      }
      
      // إنشاء عنصر لكل مقطع
      for (let i = 0; i < analysisSegments.length; i++) {
        const segment = analysisSegments[i];
        
        // تحليل المقطع لاستخراج الأخطاء
        const hasNumbers = segment.analysis.includes('<') && segment.analysis.includes('>');
        const hasMissing = segment.analysis.includes('__');
        const hasMeaning = segment.analysis.includes('[MEANING]');
        
        // إنشاء علامات الأخطاء
        let tagHTML = '';
        if (hasNumbers) {
          tagHTML += '<span class="segment-tag tag-error">أخطاء أرقام</span>';
        }
        if (hasMissing) {
          tagHTML += '<span class="segment-tag tag-warning">نصوص مفقودة</span>';
        }
        if (hasMeaning) {
          tagHTML += '<span class="segment-tag tag-info">اختلاف معنى</span>';
        }
        if (!hasNumbers && !hasMissing && !hasMeaning) {
          tagHTML = '<span class="segment-tag" style="background-color: #d1fae5; color: #065f46;">مطابق</span>';
        }
        
        // إنشاء عنصر المقطع
        const segmentDiv = document.createElement('div');
        segmentDiv.className = 'segment-comparison';
        
        // تطبيق التحديد على النصوص
        const sourceHighlighted = applyHighlights(segment.source, segment.analysis);
        const targetHighlighted = applyHighlights(segment.target, segment.analysis);
        
        segmentDiv.innerHTML = `
          <div class="segment-header">
            <div>المقطع ${i+1}</div>
            <div>${tagHTML}</div>
          </div>
          <div class="segment-content">
            <div class="segment-source">${sourceHighlighted}</div>
            <div class="segment-target">${targetHighlighted}</div>
          </div>
          <div class="segment-notes">
            <strong>ملاحظات:</strong> ${formatAnalysisText(segment.analysis)}
          </div>
        `;
        
        container.appendChild(segmentDiv);
      }
    }

    /* =====================================
       دوال مساعدة للتعامل مع النصوص
    ===================================== */
    // حساب عدد الكلمات في النص
    function countWords(text) {
      return text.trim().split(/\s+/).filter(word => word !== "").length;
    }
    // هروب أحرف Regex الخاصة
    function escapeRegExp(string) {
      return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
    }
    // تقسيم النص إلى أسطر مع عرض رقم السطر
    function splitIntoLines(text) {
      return text.split('\n').map((line, i) => `<div class="line-item"><span class="line-number">${i+1}:</span> <span class="line-text">${line}</span></div>`).join('');
    }
    // الحصول على رقم السطر لظهور عبارة معينة
    function getLineNumber(text, substring) {
      const index = text.indexOf(substring);
      if (index === -1) return "غير محدد";
      return text.substring(0, index).split("\n").length;
    }
    // اقتطاع النص إذا كان طويلا جدا
    function truncateText(text, maxLength) {
      if (text.length <= maxLength) return text;
      return text.substring(0, maxLength) + '...';
    }
    // تنسيق نص التحليل بتمييز الكلمات المهمة
    function formatAnalysisText(text) {
      // تمييز الكلمات المهمة مثل "الأرقام" و "المفقودة" و "المعنى"
      text = text.replace(/الأرقام/g, '<span class="font-bold text-indigo-600">الأرقام</span>');
      text = text.replace(/المفقودة/g, '<span class="font-bold text-pink-600">المفقودة</span>');
      text = text.replace(/المعنى/g, '<span class="font-bold text-green-600">المعنى</span>');
      
      // تحديد علامات التمييز
      text = text.replace(/<([^<>]+)>/g, '<span class="highlight-number">&#x3C;$1&#x3E;</span>');
      text = text.replace(/__(.*?)__/g, '<span class="highlight-missing">__$1__</span>');
      text = text.replace(/\[MEANING\](.*?)\[\/MEANING\]/g, '<span class="highlight-meaning">$1</span>');
      
      return text;
    }
    // تمييز الكلمة المتزامنة في النص
    function highlightSyncWord(text, syncWord) {
      if (!syncWord || !text.includes(syncWord)) return text;
      
      // تجنب تمييز الكلمة إذا كانت جزءًا من كلمة أكبر
      const regex = new RegExp(`(\\b${escapeRegExp(syncWord)}\\b)`, 'g');
      // جعل الظهور الأخير للكلمة ممَيز
      const lastIndex = text.lastIndexOf(syncWord);
      if (lastIndex !== -1) {
        const beforeSync = text.substring(0, lastIndex);
        const afterSync = text.substring(lastIndex + syncWord.length);
        return beforeSync + '<span class="sync-word">' + syncWord + '</span>' + afterSync;
      }
      
      return text;
    }

    /* =====================================
       دوال التمييز (Highlighting) للنتائج
    ===================================== */
    // دالة محسنة لتحديد النصوص التي بها مشاكل فقط على الأسطر المتأثرة
    function applyHighlights(originalText, analysisOutput) {
      // استخراج النصوص التي بها مشاكل من التحليل
      const numberMatches = Array.from(analysisOutput.matchAll(/<([^<>]+)>/g)).map(m => m[1].trim());
      const missingMatches = Array.from(analysisOutput.matchAll(/__(.*?)__/g)).map(m => m[1].trim());
      const meaningMatches = Array.from(analysisOutput.matchAll(/\[MEANING\](.*?)\[\/MEANING\]/g)).map(m => m[1].trim());
  
      // تقسيم النص الأصلي إلى أسطر
      const lines = originalText.split('\n');

      // معالجة كل سطر على حدة وتطبيق التحديد إذا وُجدت مشكلة
      const highlightedLines = lines.map(line => {
        // تحديد اختلافات الأرقام
        numberMatches.forEach(phrase => {
          if (line.includes(phrase)) {
            const regex = new RegExp(escapeRegExp(phrase), 'g');
            line = line.replace(regex, `<span class="highlight-number">${phrase}</span>`);
          }
        });
        // تحديد النصوص المفقودة
        missingMatches.forEach(phrase => {
          if (line.includes(phrase)) {
            const regex = new RegExp(escapeRegExp(phrase), 'g');
            line = line.replace(regex, `<span class="highlight-missing">__${phrase}__</span>`);
          }
        });
        // تحديد اختلافات المعنى
        meaningMatches.forEach(phrase => {
          if (line.includes(phrase)) {
            const regex = new RegExp(escapeRegExp(phrase), 'g');
            line = line.replace(regex, `<span class="highlight-meaning">${phrase}</span>`);
          }
        });
        return line;
      });

      return highlightedLines.join('\n');
    }

    /* =====================================
       دالة توليد الشرح التفصيلي Organized Explanation
       يتم تقسيم الشرح إلى خطوات منظمة
    ===================================== */
    function generateExplanation(sourceText, analysisOutput) {
      let steps = [];
      // الخطوة 1: النصوص المفقودة
      const missingRegex = /__(.*?)__/g;
      let match;
      while ((match = missingRegex.exec(analysisOutput)) !== null) {
        const phrase = match[1].trim();
        if (phrase) {
          const lineNum = getLineNumber(sourceText, phrase);
          steps.push(`<li><strong>الخطوة 1:</strong> في السطر ${lineNum}، الجزء "<span class="highlight-missing">__${phrase}__</span>" من النص المصدر مفقود في النص الهدف. تأكد من إضافته لتحسين الدقة.</li>`);
        }
      }
      // الخطوة 2: اختلافات الأرقام
      const numberRegex = /<([^<>]+)>/g;
      while ((match = numberRegex.exec(analysisOutput)) !== null) {
        const phrase = match[1].trim();
        if (phrase) {
          const lineNum = getLineNumber(sourceText, phrase);
          steps.push(`<li><strong>الخطوة 2:</strong> في السطر ${lineNum}، الرقم "<span class="highlight-number">${phrase}</span>" في المصدر لا يتطابق مع الرقم في الهدف. يرجى المراجعة.</li>`);
        }
      }
      // الخطوة 3: اختلافات المعنى
      const meaningRegex = /\[MEANING\](.*?)\[\/MEANING\]/g;
      while ((match = meaningRegex.exec(analysisOutput)) !== null) {
        const phrase = match[1].trim();
        if (phrase) {
          const lineNum = getLineNumber(sourceText, phrase);
          steps.push(`<li><strong>الخطوة 3:</strong> في السطر ${lineNum}، تم العثور على اختلاف في المعنى مع التعبير "<span class="highlight-meaning">${phrase}</span>". تحقق من الدقة.</li>`);
        }
      }
      // إذا لم يكن هناك اختلافات
      if (steps.length === 0) {
        return `<p>النصوص متطابقة تماماً ولا توجد فروقات تحتاج للتنبيه.</p>`;
      }
      return `<ol class="list-decimal ml-6 space-y-2">${steps.join('')}</ol>`;
    }

    /* =====================================
       دالة معالجة الملفات (PDF و DOCX)
    ===================================== */
    async function processFile(file) {
      let text = "";
      if (file.type === 'application/pdf') {
        const form = new FormData();
        form.append('image', file);
        const response = await fetch('https://demo.api4ai.cloud/ocr/v1/results', {
          method: 'POST',
          body: form,
          headers: { 'A4A-CLIENT-APP-ID': 'sample' }
        });
        const data = await response.json();
        text = data.results[0].entities[0].objects[0].entities[0].text;
      } else if (file.type === 'application/vnd.openxmlformats-officedocument.wordprocessingml.document') {
        const arrayBuffer = await file.arrayBuffer();
        const result = await mammoth.extractRawText({ arrayBuffer });
        text = result.value;
      } else {
        throw new Error('نوع الملف غير مدعوم');
      }
      return text;
    }

    /* =====================================
       دوال رفع الملفات وإدخال النصوص
    ===================================== */
    // رفع ملف السورس
    document.getElementById('sourceFile')?.addEventListener('change', async (event) => {
      const file = event.target.files[0];
      if (!file) return;
      document.getElementById('processStatus').classList.remove('hidden');
      try {
        const text = await processFile(file);
        document.getElementById('sourceText').value = text;
      } catch (error) {
        console.error('Error processing source file:', error);
        addError('خطأ في معالجة ملف السورس');
      } finally {
        document.getElementById('processStatus').classList.add('hidden');
      }
    });
    // رفع ملف التارجت
    document.getElementById('targetFile')?.addEventListener('change', async (event) => {
      const file = event.target.files[0];
      if (!file) return;
      document.getElementById('processStatus').classList.remove('hidden');
      try {
        const text = await processFile(file);
        document.getElementById('targetText').value = text;
      } catch (error) {
        console.error('Error processing target file:', error);
        addError('خطأ في معالجة ملف التارجت');
      } finally {
        document.getElementById('processStatus').classList.add('hidden');
      }
    });
    // رفع ملف المصادر الإضافية
    document.getElementById('sourceExtraFile')?.addEventListener('change', async (event) => {
      const file = event.target.files[0];
      if (!file) return;
      document.getElementById('processStatus').classList.remove('hidden');
      try {
        const text = await processFile(file);
        document.getElementById('sourceExtraText').value = text;
      } catch (error) {
        console.error('Error processing extra source file:', error);
        addError('خطأ في معالجة ملف المصدر الإضافي');
      } finally {
        document.getElementById('processStatus').classList.add('hidden');
      }
    });

    /* =====================================
       دالة عرض الأخطاء والرسائل
    ===================================== */
    function addError(message, type = 'error') {
      const errorsList = document.getElementById('errorsList');
      if (!errorsList) return;
      const errorDiv = document.createElement('div');
      errorDiv.className = `p-4 rounded-xl ${type === 'error' ? 'bg-red-50 text-red-700' : 'bg-yellow-50 text-yellow-700'}`;
      errorDiv.innerHTML = `<div class="flex items-center">
                              <i class="fas fa-${type === 'error' ? 'exclamation-circle' : 'info-circle'} ml-2 text-${type === 'error' ? 'red' : 'yellow'}-500"></i>
                              <span>${message}</span>
                            </div>`;
      errorsList.appendChild(errorDiv);
    }

    /* =====================================
       معالجة عملية التحليل عند الضغط على الزر
    ===================================== */
    document.getElementById('submitBtn').addEventListener('click', async () => {
      const sourceText = document.getElementById('sourceText').value;
      const targetText = document.getElementById('targetText').value;
      // مسح الرسائل السابقة وإظهار النتائج
      document.getElementById('errorsList').innerHTML = '';
      document.getElementById('resultSection').classList.remove('hidden');
      document.getElementById('explanationBox').classList.remove('hidden');
  
      if (!sourceText || !targetText) {
        addError('يرجى إدخال كلا النصين المصدر والهدف');
        return;
      }
  
      // مقارنة عدد الكلمات وتنبيه إن وجد اختلاف
      const sourceWordCount = countWords(sourceText);
      const targetWordCount = countWords(targetText);
      if (sourceWordCount !== targetWordCount) {
        addError(`عدد كلمات النص المصدر (${sourceWordCount}) يختلف عن النص الهدف (${targetWordCount})`, 'warning');
      }
  
      try {
        // عرض مؤشر التقدم الأولي
        const initialProgressDiv = document.createElement('div');
        initialProgressDiv.className = "bg-indigo-100 p-4 rounded-xl mb-4";
        initialProgressDiv.innerHTML = `<div class="flex items-center">
                                          <div class="animate-spin h-6 w-6 border-4 border-indigo-600 rounded-full border-t-transparent ml-3"></div>
                                          <span>جارٍ تقسيم النصوص للتحليل...</span>
                                        </div>`;
        document.getElementById('errorsList').appendChild(initialProgressDiv);
        
        // تقسيم النصوص إلى أجزاء
        const sourceSegments = await divideTextWithChatGPT(sourceText);
        const targetSegments = await divideTextWithChatGPT(targetText);
        
        // التحقق من عدد الأجزاء
        if (sourceSegments.length !== targetSegments.length) {
          // إذا كان عدد الأجزاء مختلفًا، نقوم بتعديل التقسيم
          const maxSegments = Math.max(sourceSegments.length, targetSegments.length);
          const minSegments = Math.min(sourceSegments.length, targetSegments.length);
          
          // إضافة رسالة تحذير
          addError(`تم تعديل تقسيم النصوص لضمان التطابق (${sourceSegments.length} مقابل ${targetSegments.length})`, 'warning');
          
          // تعديل المصفوفة الأقصر
          if (sourceSegments.length < targetSegments.length) {
            // دمج الأجزاء الزائدة في التارجت مع الجزء الأخير من السورس
            const extraSegments = targetSegments.slice(minSegments);
            targetSegments.splice(minSegments, extraSegments.length, extraSegments.join('\n\n'));
          } else {
            // دمج الأجزاء الزائدة في السورس مع الجزء الأخير من التارجت
            const extraSegments = sourceSegments.slice(minSegments);
            sourceSegments.splice(minSegments, extraSegments.length, extraSegments.join('\n\n'));
          }
        }
        
        initialProgressDiv.remove();
        
        // تحليل الأجزاء
        fullAnalysisText = await analyzeTextSegments(sourceSegments, targetSegments);
        
        // عرض النتائج
        document.getElementById('sourceTextReview').innerHTML = applyHighlights(sourceText, fullAnalysisText);
        document.getElementById('targetTextReview').innerHTML = applyHighlights(targetText, fullAnalysisText);
        
        // عرض الشرح التفصيلي
        document.getElementById('explanationText').innerHTML = generateExplanation(sourceText, fullAnalysisText);
        
        // عرض المقاطع في طريقة العرض المقسمة
        displaySegmentedView();
        
        // إعداد المسودة
        await displayDraftSections();
        
      } catch (error) {
        console.error('Error during analysis:', error);
        addError('حدث خطأ أثناء التحليل: ' + error.message);
      }
    });

    /* =====================================
       التبديل بين طرق العرض المختلفة
    ===================================== */
    document.querySelectorAll('.view-tab').forEach(tab => {
      tab.addEventListener('click', function() {
        // إزالة الفئة النشطة من جميع علامات التبويب
        document.querySelectorAll('.view-tab').forEach(t => t.classList.remove('active'));
        // إضافة الفئة النشطة إلى علامة التبويب المحددة
        this.classList.add('active');
        
        // إخفاء جميع محتويات العرض
        document.querySelectorAll('.view-content').forEach(content => content.classList.remove('active'));
        // إظهار محتوى العرض المحدد
        const tabId = this.getAttribute('data-tab');
        document.getElementById(tabId).classList.add('active');
      });
    });

    /* =====================================
       التبديل بين عرض وإخفاء المسودة
    ===================================== */
    document.getElementById('toggleDraftBtn').addEventListener('click', function() {
      const draftSection = document.getElementById('fullTextDraftSection');
      draftSection.classList.toggle('hidden');
    });

    /* =====================================
       تنزيل التقرير بصيغة Excel
    ===================================== */
    document.getElementById('downloadExcelBtn').addEventListeneهةبr('click', function() {
      // هنا يمكن إضافة كود لتنزيل التقرير بصيغة Excel
      alert('سيتم تنفيذ تنزيل التقرير بصيغة Excel قريبًا');
    });

    /* =====================================
       تنزيل التقرير بصيغة Word
    ===================================== */
    document.getElementById('downloadWordBtn').addEventListener('click', function() {
      // هنا يمكن إضافة كود لتنزيل التقرير بصيغة Word
      alert('سيتم تنفيذ تنزيل التقرير بصيغة Word قريبًا');
    });
  </script>
</body>
</html>