File size: 31,705 Bytes
d0d3666
 
 
 
 
27d42c0
 
d0d3666
c6156df
27d42c0
 
 
d0d3666
27d42c0
d0d3666
 
 
 
 
 
 
 
 
 
27d42c0
 
59b39d8
 
7359e36
 
 
59b39d8
27d42c0
 
d0d3666
 
27d42c0
81565ac
babba69
 
 
 
7359e36
27d42c0
7359e36
babba69
 
 
 
27d42c0
 
dfb5957
 
 
 
 
27d42c0
 
6aefe85
b5ef197
f5f0451
27d42c0
6aefe85
 
 
27d42c0
b5ef197
d0d3666
27d42c0
 
6903f30
b5ef197
27d42c0
b5ef197
27d42c0
b5ef197
27d42c0
bf7e722
27d42c0
 
 
 
 
 
1f458a4
27d42c0
1f458a4
27d42c0
1f458a4
d0d3666
 
27d42c0
d0d3666
27d42c0
 
b5ef197
27d42c0
 
b5ef197
27d42c0
 
b5ef197
d0d3666
 
27d42c0
b5ef197
27d42c0
 
 
 
 
d0d3666
27d42c0
b5ef197
27d42c0
 
 
 
 
d0d3666
 
b5ef197
27d42c0
 
 
 
 
d0d3666
 
 
27d42c0
 
 
 
d0d3666
 
27d42c0
 
d0d3666
27d42c0
 
d0d3666
27d42c0
d0d3666
 
27d42c0
 
d0d3666
27d42c0
59b39d8
 
27d42c0
 
 
 
 
 
59b39d8
27d42c0
5643379
27d42c0
 
 
 
 
59b39d8
 
 
 
27d42c0
 
59b39d8
27d42c0
d0d3666
 
27d42c0
 
 
 
 
 
 
c6156df
27d42c0
 
 
 
 
 
 
 
 
 
 
 
 
 
d0d3666
27d42c0
 
 
d0d3666
27d42c0
d0d3666
 
27d42c0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d0d3666
 
27d42c0
 
d0d3666
f5f0451
 
27d42c0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c6156df
27d42c0
 
c6156df
27d42c0
6903f30
35d533d
 
 
 
 
27d42c0
 
f5f0451
 
27d42c0
f5f0451
 
27d42c0
 
f5f0451
 
 
a3fda14
f5f0451
 
27d42c0
 
f5f0451
a3fda14
 
 
f5f0451
27d42c0
 
 
 
f5f0451
27d42c0
f5f0451
 
35d533d
 
 
a3fda14
35d533d
 
368929a
27d42c0
7359e36
 
35d533d
 
 
a3fda14
35d533d
 
368929a
27d42c0
 
 
dfb5957
 
27d42c0
dfb5957
 
 
 
35d533d
f5f0451
27d42c0
 
f5f0451
27d42c0
7359e36
 
dfb5957
27d42c0
 
6903f30
 
27d42c0
f5f0451
 
 
 
27d42c0
f5f0451
368929a
6903f30
f5f0451
 
 
 
 
27d42c0
f5f0451
d0d3666
6903f30
dfb5957
 
 
 
 
27d42c0
dfb5957
 
27d42c0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
368929a
27d42c0
f5f0451
27d42c0
 
f5f0451
 
 
 
27d42c0
f5f0451
 
 
 
 
 
 
 
 
 
27d42c0
f5f0451
 
 
27d42c0
 
 
 
 
 
 
 
 
 
 
f5f0451
 
 
 
 
 
368929a
f5f0451
 
27d42c0
 
f5f0451
 
 
 
 
 
 
 
 
 
 
 
 
368929a
f5f0451
27d42c0
e75e1b2
f5f0451
 
6903f30
27d42c0
 
f5f0451
 
 
 
 
 
 
 
 
 
 
27d42c0
 
 
 
 
 
 
 
 
 
c6156df
27d42c0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f5f0451
 
 
 
 
27d42c0
f5f0451
 
 
368929a
27d42c0
f5f0451
 
 
 
 
27d42c0
f5f0451
 
27d42c0
 
 
 
f5f0451
 
27d42c0
f5f0451
 
 
27d42c0
f5f0451
 
 
27d42c0
f5f0451
 
 
 
 
 
27d42c0
6903f30
f5f0451
 
6903f30
f5f0451
 
 
 
27d42c0
 
 
368929a
f5f0451
 
 
27d42c0
c6156df
f5f0451
 
 
27d42c0
f5f0451
 
 
27d42c0
f5f0451
27d42c0
f5f0451
 
27d42c0
1f458a4
f5f0451
27d42c0
89b3f72
27d42c0
 
 
 
f5f0451
 
 
368929a
f5f0451
27d42c0
 
 
 
 
 
f5f0451
d0d3666
 
27d42c0
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
<!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 CSS, FontAwesome, Mammoth وSheetJS وjsPDF -->
  <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>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.17.4/xlsx.full.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.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(0,0,0,0.2); }
      70% { box-shadow: 0 0 0 10px rgba(0,0,0,0); }
      100% { box-shadow: 0 0 0 0 rgba(0,0,0,0); }
    }
    
    /* تنسيق النصوص والتظليل */
    .text-comparison { line-height: 1.8; white-space: pre-wrap; }
    .highlight-missing {
      background-color: #f87171;
      color: #fff;
      padding: 0 4px;
      border-radius: 3px;
      font-weight: bold;
    }
    .highlight-number {
      background-color: #facc15;
      color: #000;
      padding: 0 4px;
      border-radius: 3px;
      font-weight: bold;
    }
    .highlight-abbreviation {
      background-color: #34d399;
      color: #fff;
      padding: 0 4px;
      border-radius: 3px;
      font-weight: bold;
    }
    
    /* تقسيم الفقرات وترقيمها */
    .line-item {
      margin-bottom: 1rem;
      padding: 0.5rem;
      border-bottom: 1px dashed #ccc;
    }
    .line-number {
      font-weight: bold;
      color: #4B5563;
      margin-left: 0.5rem;
    }
    .line-text { display: inline-block; }
    
    /* تصميم البطاقات */
    .card {
      background-color: #fff;
      border-radius: 1rem;
      box-shadow: 0 10px 25px -5px rgba(0,0,0,0.1);
      padding: 2rem;
      border: 1px solid #f3f4f6;
    }
    .card-hover:hover {
      box-shadow: 0 10px 25px -5px rgba(0,0,0,0.2);
      transform: translateY(-3px);
    }
    .icon { margin-left: 0.5rem; }
    .upload-label {
      display: flex;
      flex-direction: row-reverse;
      align-items: center;
      justify-content: center;
    }
  </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-800 via-purple-800 to-pink-800 animate-gradient text-white py-12 mb-12 shadow-2xl">
      <div class="max-w-6xl mx-auto px-4 text-center">
        <h1 class="text-6xl font-extrabold mb-4 animate-scale">
          منصة مراجعة النصوص والترجمات <i class="fas fa-chart-line icon"></i>
        </h1>
        <p class="text-2xl opacity-90">
          تحليل دقيق يشمل النصوص المفقودة، الأرقام/التواريخ، وفهم الاختصارات مع تحدٍ استخراج الأخطاء
        </p>
      </div>
    </header>
    
    <!-- المحتوى الرئيسي -->
    <main class="max-w-7xl mx-auto px-4 space-y-10">
      <!-- رفع الملفات وإدخال النصوص -->
      <div class="card card-hover">
        <h2 class="text-3xl font-bold text-gray-800 border-b pb-3 mb-6">
          <i class="fas fa-file-upload icon text-indigo-600"></i> تحميل الملفات / إدخال النصوص
        </h2>
        <div class="grid grid-cols-1 md:grid-cols-2 gap-8">
          <!-- ملف المصدر -->
          <div class="group border-2 border-dashed border-indigo-300 rounded-xl p-10 text-center bg-indigo-50 hover:bg-indigo-100 transition-colors duration-300">
            <label class="cursor-pointer block upload-label">
              <input type="file" id="sourceFile" accept=".docx,.pdf,.xlsx,.xls" class="hidden">
              <span class="text-xl text-indigo-600 group-hover:text-indigo-700">ملف المصدر</span>
              <i class="fas fa-upload text-6xl text-indigo-500 mb-4"></i>
            </label>
          </div>
          <!-- ملف الهدف -->
          <div class="group border-2 border-dashed border-pink-300 rounded-xl p-10 text-center bg-pink-50 hover:bg-pink-100 transition-colors duration-300">
            <label class="cursor-pointer block upload-label">
              <input type="file" id="targetFile" accept=".docx,.pdf,.xlsx,.xls" class="hidden">
              <span class="text-xl text-pink-600 group-hover:text-pink-700">ملف الهدف</span>
              <i class="fas fa-download text-6xl text-pink-500 mb-4"></i>
            </label>
          </div>
        </div>
        <div id="processStatus" class="hidden mt-6">
          <div class="flex items-center justify-end space-x-3 bg-indigo-100 rounded-xl p-4">
            <span class="text-xl text-indigo-700">جارٍ معالجة الملف...</span>
            <div class="animate-spin h-10 w-10 border-4 border-indigo-600 rounded-full border-t-transparent"></div>
          </div>
        </div>
        <div class="mt-8 grid grid-cols-1 md:grid-cols-2 gap-8">
          <!-- إدخال النصوص يدويًا -->
          <div class="group">
            <label class="block text-2xl font-bold text-gray-700 mb-4">
              <i class="fas fa-language icon text-indigo-600"></i> النص المصدر
            </label>
            <textarea id="sourceText" dir="rtl" class="w-full px-8 py-6 border-2 border-gray-200 rounded-xl focus:ring-indigo-200 focus:border-indigo-400 transition-all resize-none text-xl" rows="8" placeholder="اكتب النص المصدر هنا..."></textarea>
          </div>
          <div class="group">
            <label class="block text-2xl font-bold text-gray-700 mb-4">
              <i class="fas fa-language icon text-pink-600"></i> النص الهدف
            </label>
            <textarea id="targetText" dir="ltr" class="w-full px-8 py-6 border-2 border-gray-200 rounded-xl focus:ring-pink-200 focus:border-pink-400 transition-all resize-none text-xl" rows="8" placeholder="اكتب النص الهدف هنا..."></textarea>
          </div>
        </div>
      </div>
      
      <!-- المصادر الإضافية -->
      <div class="card card-hover">
        <h2 class="text-3xl font-bold text-gray-800 border-b pb-3 mb-6">
          <i class="fas fa-book-open icon text-green-600"></i> مصادر إضافية
        </h2>
        <div class="grid grid-cols-1 md:grid-cols-2 gap-8">
          <!-- رفع ملف المصادر -->
          <div class="group border-2 border-dashed border-green-300 rounded-xl p-10 text-center bg-green-50 hover:bg-green-100 transition-colors duration-300">
            <label class="cursor-pointer block upload-label">
              <input type="file" id="sourceExtraFile" accept=".docx,.pdf,.xlsx,.xls" class="hidden">
              <span class="text-xl text-green-600 group-hover:text-green-700">تحميل ملف المصادر</span>
              <i class="fas fa-upload text-6xl text-green-500 mb-4"></i>
            </label>
          </div>
          <!-- إدخال المصادر يدويًا -->
          <div class="group">
            <label class="block text-2xl font-bold text-gray-700 mb-4">
              <i class="fas fa-edit icon text-green-600"></i> إدخال المصادر يدويًا
            </label>
            <textarea id="sourceExtraText" dir="rtl" class="w-full px-8 py-6 border-2 border-green-200 rounded-xl focus:ring-green-200 focus:border-green-400 transition-all resize-none text-xl" rows="8" placeholder="اكتب المصادر هنا..."></textarea>
          </div>
        </div>
      </div>
      
      <!-- زر التحليل والمراجعة -->
      <button id="submitBtn" class="w-full bg-gradient-to-r from-indigo-700 to-pink-700 hover:from-indigo-800 hover:to-pink-800 text-white font-bold py-6 px-10 rounded-xl transition-all transform hover:scale-105 focus:ring-indigo-200 text-2xl shadow-2xl hover:shadow-2xl pulse-animation">
        <div class="flex items-center justify-center">
          <span>تحليل ومراجعة النصوص</span>
          <i class="fas fa-sync-alt icon mr-4"></i>
        </div>
      </button>
      
      <!-- عرض النتائج -->
      <div id="resultSection" class="card hidden">
        <h2 class="text-3xl font-bold text-gray-800 border-b pb-4 mb-6">
          <i class="fas fa-search icon text-green-600"></i> نتائج التحليل والمقارنة
        </h2>
        <div id="errorsList" class="space-y-4 mb-6"></div>
        <div class="grid grid-cols-1 md:grid-cols-2 gap-8">
          <div>
            <h4 class="text-2xl font-bold text-gray-700 mb-4">
              <i class="fas fa-file-alt icon text-indigo-600"></i> النص المصدر (مع التعليم)
            </h4>
            <div id="sourceTextReview" class="bg-indigo-50 rounded-xl p-8 min-h-[250px] border-2 border-indigo-200 text-comparison"></div>
          </div>
          <div>
            <h4 class="text-2xl font-bold text-gray-700 mb-4">
              <i class="fas fa-file-alt icon text-pink-600"></i> النص الهدف (بدون تعليم)
            </h4>
            <div id="targetTextReview" class="bg-gray-50 rounded-xl p-8 min-h-[250px] border-2 border-gray-300 text-comparison"></div>
          </div>
        </div>
        <div id="explanationBox" class="mt-8">
          <h2 class="text-3xl font-bold text-gray-800 border-b pb-4 mb-6">
            <i class="fas fa-info-circle icon text-green-600"></i> شرح الاختلافات
          </h2>
          <div id="explanationText" class="text-2xl text-gray-700"></div>
        </div>
      </div>
      
      <!-- قسم معلومات المترجم والتقييم وتنزيل التقرير وإعادة المراجعة -->
      <div id="reportSection" class="card hidden">
        <h2 class="text-3xl font-bold text-gray-800 border-b pb-4 mb-6">
          معلومات وتقرير المراجعة
        </h2>
        <div class="grid grid-cols-1 md:grid-cols-3 gap-6 mb-6">
          <div>
            <label class="block text-2xl font-bold text-gray-700 mb-2">اسم/كود المترجم</label>
            <input id="translatorName" type="text" class="w-full px-4 py-3 border-2 border-gray-300 rounded-xl focus:ring-indigo-200 focus:border-indigo-400 text-xl" placeholder="أدخل اسم المترجم أو الكود">
          </div>
          <div>
            <label class="block text-2xl font-bold text-gray-700 mb-2">التقييم</label>
            <select id="translatorRating" class="w-full px-4 py-3 border-2 border-gray-300 rounded-xl focus:ring-indigo-200 focus:border-indigo-400 text-xl">
              <option value="5">5 - ممتاز</option>
              <option value="4">4 - جيد جداً</option>
              <option value="3">3 - جيد</option>
              <option value="2">2 - متوسط</option>
              <option value="1">1 - ضعيف</option>
            </select>
          </div>
          <div class="flex flex-col justify-end">
            <button id="reReviewBtn" class="w-full bg-yellow-500 hover:bg-yellow-600 text-white font-bold py-3 px-4 rounded-xl transition-all text-xl shadow-lg">
              إعادة المراجعة
            </button>
          </div>
        </div>
        <div class="flex items-center justify-around">
          <button id="downloadPdfBtn" class="bg-green-600 hover:bg-green-700 text-white font-bold py-3 px-6 rounded-xl transition-all text-xl shadow-lg">
            تنزيل التقرير PDF
          </button>
          <button id="downloadWordBtn" class="bg-blue-600 hover:bg-blue-700 text-white font-bold py-3 px-6 rounded-xl transition-all text-xl shadow-lg">
            تنزيل التقرير Word
          </button>
        </div>
      </div>
      
    </main>
  </div>
  
  <!-- جافا سكريبت: الوظائف والتحليل وتنزيل التقرير -->
  <script>
    (function() {
      "use strict";
      
      // تعريف البرومت مع التعليمات والتحدي والمكافأة/العقاب
      const ANALYSIS_PROMPT = `أنت خبير لغوي وتقني متخصص في مراجعة الترجمة وتحليل النصوص بدقة عالية.
أمامك تحدٍ حقيقي: يجب عليك استخراج كافة الاختلافات الموجودة بين النص المصدر والنص الهدف بدقة تامة.
إذا كانت النصوص متطابقة تماماً، أرجع [MATCH] فقط.
أما إذا كانت هناك اختلافات، فحدد الأنواع التالية بدقة:
1. النصوص المفقودة: الكلمات أو العبارات الموجودة في النص المصدر وغير موجودة في النص الهدف.
2. الأرقام والتواريخ: التي يجب أن تكون مطابقة بين النصين؛ وفي حال وجود اختلاف، قم بالإشارة إليه.
3. اختلاف المعنى: إذا كانت الترجمة تحمل معنى مختلفاً عن النص المصدر.
4. الاختصارات: يجب فهمها وتحليلها بدقة دون اعتبارها خطأ إذا كانت مستخدمة بشكل سليم.
  
استخدم العلامات التالية لتعليم النص المصدر فقط:
- النصوص المفقودة بين علامتي __ و __.
- الأرقام والتواريخ بين علامتي < و >.
- اختلاف المعنى بين علامتي [MEANING] و [/MEANING].
- الاختصارات بين علامتي {ABBR} و {/ABBR}.

إذا تمكنت من استخراج كافة الاختلافات المطلوبة بدقة، أرجو إرجاع الناتج مع الرسالة "مكافأة: لقد نجحت في التحدي!".
أما إذا أخفقت في استخراج الاختلافات أو أدرجت أخطاء غير موجودة، أرجو إرجاع الناتج مع الرسالة "عقوبة: فشلت في التحدي!".

قدم الناتج في شكل قائمة مفصلة مع شرح مختصر لكل اختلاف وذكر رقم السطر إن أمكن.

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

النص الهدف:
{target}`;
      
      // دوال مساعدة عامة
      const countWords = text =>
        text.trim().split(/\s+/).filter(word => word !== "").length;
      
      const escapeRegExp = string =>
        string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
      
      // تقسيم النص إلى فقرات مرقمة
      const splitIntoLines = text =>
        text.split(/\n+/).map((line, i) => {
          line = line.trim();
          if(line && !line.endsWith('.')) { line += '.'; }
          return `<div class="line-item"><span class="line-number">${i+1}:</span><span class="line-text">${line}</span></div>`;
        }).join('');
      
      // الحصول على رقم السطر الذي يحتوي على عبارة معينة
      const getLineNumber = (text, substring) => {
        const index = text.indexOf(substring);
        if (index === -1) return "غير محدد";
        return text.substring(0, index).split("\n").length;
      };
      
      // تطبيق التظليل على النص المصدر بناءً على نتائج التحليل
      const applyHighlights = (originalText, analysisOutput) => {
        let highlightedText = originalText;
        let match;
        // تظليل النصوص المفقودة
        const missingRegex = /__(.*?)__/g;
        while ((match = missingRegex.exec(analysisOutput)) !== null) {
          const phrase = match[1].trim();
          if (phrase) {
            const replacement = `<span class="highlight-missing">${phrase}</span>`;
            const phraseRegex = new RegExp(escapeRegExp(phrase), 'g');
            highlightedText = highlightedText.replace(phraseRegex, replacement);
          }
        }
        // تظليل الأرقام والتواريخ
        const numberRegex = /<([^<>]+)>/g;
        while ((match = numberRegex.exec(analysisOutput)) !== null) {
          const phrase = match[1].trim();
          if (phrase) {
            const replacement = `<span class="highlight-number">${phrase}</span>`;
            const phraseRegex = new RegExp(escapeRegExp(phrase), 'g');
            highlightedText = highlightedText.replace(phraseRegex, replacement);
          }
        }
        // تظليل الاختصارات
        const abbrRegex = /{ABBR}(.*?){\/ABBR}/g;
        while ((match = abbrRegex.exec(analysisOutput)) !== null) {
          const phrase = match[1].trim();
          if (phrase) {
            const replacement = `<span class="highlight-abbreviation">${phrase}</span>`;
            const phraseRegex = new RegExp(escapeRegExp(phrase), 'g');
            highlightedText = highlightedText.replace(phraseRegex, replacement);
          }
        }
        return highlightedText;
      };
      
      // توليد شرح تفصيلي للاختلافات
      const generateExplanation = (sourceText, analysisOutput) => {
        let explanations = [];
        const iconMissing = `<i class="fas fa-exclamation-triangle mr-1"></i>`;
        const iconNumber = `<i class="fas fa-hashtag mr-1"></i>`;
        const iconMeaning = `<i class="fas fa-info-circle mr-1"></i>`;
        const iconAbbr = `<i class="fas fa-font mr-1"></i>`;
        
        // شرح النصوص المفقودة
        const missingRegex = /__(.*?)__/g;
        let match;
        while ((match = missingRegex.exec(analysisOutput)) !== null) {
          const phrase = match[1].trim();
          if (phrase) {
            const lineNum = getLineNumber(sourceText, phrase);
            explanations.push(`<p>${iconMissing} في السطر ${lineNum}: النص المفقود <span class="highlight-missing">${phrase}</span></p>`);
          }
        }
        // شرح الأرقام والتواريخ
        const numberRegex = /<([^<>]+)>/g;
        while ((match = numberRegex.exec(analysisOutput)) !== null) {
          const phrase = match[1].trim();
          if (phrase) {
            const lineNum = getLineNumber(sourceText, phrase);
            explanations.push(`<p>${iconNumber} في السطر ${lineNum}: الرقم/التاريخ <span class="highlight-number">${phrase}</span></p>`);
          }
        }
        // شرح اختلاف المعنى
        const meaningRegex = /\[MEANING\](.*?)\[\/MEANING\]/g;
        while ((match = meaningRegex.exec(analysisOutput)) !== null) {
          const phrase = match[1].trim();
          if (phrase) {
            const lineNum = getLineNumber(sourceText, phrase);
            explanations.push(`<p>${iconMeaning} في السطر ${lineNum}: اختلاف المعنى <span class="highlight-missing">${phrase}</span></p>`);
          }
        }
        // شرح الاختصارات
        const abbrRegex = /{ABBR}(.*?){\/ABBR}/g;
        while ((match = abbrRegex.exec(analysisOutput)) !== null) {
          const phrase = match[1].trim();
          if (phrase) {
            const lineNum = getLineNumber(sourceText, phrase);
            explanations.push(`<p>${iconAbbr} في السطر ${lineNum}: الاختصار <span class="highlight-abbreviation">${phrase}</span></p>`);
          }
        }
        
        // التحقق من استخدام المصادر الخارجية (في حال تم استخدامها)
        const usedSource = analysisOutput.includes('[USED_SOURCE]');
        let sourceNote = usedSource ? `<p><i class="fas fa-book-reader mr-1"></i> تم استخدام مصادر خارجية لشرح الاختصارات والمصطلحات.</p>` 
                                      : `<p><i class="fas fa-book mr-1"></i> لم يتم استخدام مصادر خارجية.</p>`;
        
        if (explanations.length === 0) {
          return `<p><i class="fas fa-check-circle mr-2"></i> لا توجد اختلافات ملحوظة بين النصين.</p>` + sourceNote;
        }
        return explanations.join('') + sourceNote;
      };
      
      // دالة معالجة الملفات (PDF, DOCX, Excel)
      const processFile = async file => {
        let text = "";
        try {
          if (file.type === 'application/pdf') {
            // استخدام OCR لـ 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') {
            // معالجة ملفات DOCX
            const arrayBuffer = await file.arrayBuffer();
            const result = await mammoth.extractRawText({ arrayBuffer });
            text = result.value;
          } else if (file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' || file.type === 'application/vnd.ms-excel') {
            // معالجة ملفات Excel باستخدام SheetJS
            const arrayBuffer = await file.arrayBuffer();
            const workbook = XLSX.read(arrayBuffer, { type: 'array' });
            let sheetData = [];
            workbook.SheetNames.forEach(sheetName => {
              const sheet = workbook.Sheets[sheetName];
              const html = XLSX.utils.sheet_to_html(sheet);
              sheetData.push(html);
            });
            text = sheetData.join('\n');
          } else {
            throw new Error('نوع الملف غير مدعوم');
          }
        } catch (error) {
          console.error('Error processing file:', error);
          throw error;
        }
        return text;
      };
      
      // التعامل مع رفع الملفات وإدخال النصوص
      const processFileInput = (inputId, targetTextAreaId, errorMsg) => {
        document.getElementById(inputId)?.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(targetTextAreaId).value = text;
          } catch (error) {
            addError(errorMsg);
          } finally {
            document.getElementById('processStatus').classList.add('hidden');
          }
        });
      };
      
      // رفع ملفات المصدر، الهدف والمصادر الإضافية
      processFileInput('sourceFile', 'sourceText', 'خطأ في معالجة ملف المصدر');
      processFileInput('targetFile', 'targetText', 'خطأ في معالجة ملف الهدف');
      processFileInput('sourceExtraFile', 'sourceExtraText', 'خطأ في معالجة ملف المصادر الإضافية');
      
      // دالة عرض الأخطاء
      const 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'} mr-2"></i>
                                <span>${message}</span>
                              </div>`;
        errorsList.appendChild(errorDiv);
      };
      
      // وظيفة تنزيل التقرير بصيغة PDF
      const downloadReportPDF = () => {
        const { jsPDF } = window.jspdf;
        const doc = new jsPDF();
        const translatorInfo = `اسم المترجم/الكود: ${document.getElementById('translatorName').value}\nالتقييم: ${document.getElementById('translatorRating').value}`;
        const errorsText = document.getElementById('explanationText').innerText;
        const report = `تقرير الأخطاء:\n\n${errorsText}\n\n${translatorInfo}`;
        doc.text(report, 10, 10);
        doc.save("تقرير_المراجعة.pdf");
      };
      
      // وظيفة تنزيل التقرير بصيغة Word
      const downloadReportWord = () => {
        const translatorInfo = `اسم المترجم/الكود: ${document.getElementById('translatorName').value}\nالتقييم: ${document.getElementById('translatorRating').value}\n\n`;
        const errorsText = document.getElementById('explanationText').innerText;
        const report = `تقرير الأخطاء:\n\n${errorsText}\n\n${translatorInfo}`;
        const blob = new Blob([report], { type: 'application/msword' });
        const link = document.createElement('a');
        link.href = URL.createObjectURL(blob);
        link.download = "تقرير_المراجعة.doc";
        link.click();
      };
      
      // إعادة المراجعة: إعادة إخفاء النتائج للسماح بإجراء مراجعة جديدة
      const reReview = () => {
        document.getElementById('resultSection').classList.add('hidden');
        document.getElementById('reportSection').classList.add('hidden');
        document.getElementById('errorsList').innerHTML = '';
        document.getElementById('sourceTextReview').innerHTML = '';
        document.getElementById('targetTextReview').innerHTML = '';
        document.getElementById('explanationText').innerHTML = '';
      };
      
      // عملية التحليل والمقارنة عند الضغط على زر التحليل
      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');
      
        if (!sourceText || !targetText) {
          addError('يرجى إدخال كلا النصين المصدر والهدف');
          return;
        }
      
        const sourceWordCount = countWords(sourceText);
        const targetWordCount = countWords(targetText);
        if (sourceWordCount !== targetWordCount) {
          addError(`عدد كلمات النص المصدر (${sourceWordCount}) يختلف عن النص الهدف (${targetWordCount})`, 'warning');
        }
      
        try {
          const progressDiv = document.createElement('div');
          progressDiv.className = "bg-indigo-100 p-4 rounded-xl mb-4";
          progressDiv.innerHTML = `<div class="flex items-center justify-end">
                                       <span class="text-xl">جارٍ التحليل...</span>
                                       <div class="animate-spin h-10 w-10 border-4 border-indigo-600 rounded-full border-t-transparent ml-4"></div>
                                     </div>`;
          document.getElementById('errorsList').appendChild(progressDiv);
      
          const prompt = ANALYSIS_PROMPT
                          .replace("{source}", sourceText)
                          .replace("{target}", targetText);
      
          const payload = {
            model: "deepseek-chat",
            messages: [
              { role: "system", content: "أنت خبير في تحليل ومراجعة النصوص بدقة عالية، وتفهم الاختصارات ومعانيها الكاملة." },
              { role: "user", content: prompt }
            ],
            temperature: 0.3,
            max_tokens: 2048,
            stream: false
          };
      
          const response = await fetch('https://api.deepseek.com/chat/completions', {
            method: 'POST',
            headers: {
              'Authorization': 'Bearer sk-15606736ed9e4aea8b7cc11a195d2b01',
              'Content-Type': 'application/json'
            },
            body: JSON.stringify(payload)
          });
      
          if (!response.ok) { 
            throw new Error('حدث خطأ بالشبكة: ' + response.statusText); 
          }
          const data = await response.json();
          const analysisOutput = data.choices[0].message.content.trim();
          progressDiv.remove();
      
          // إذا كانت النصوص متطابقة تماماً
          if (analysisOutput.includes('[MATCH]')) {
            const checkDiv = document.createElement('div');
            checkDiv.className = "p-4 rounded-xl bg-green-50 text-green-700 flex items-center";
            checkDiv.innerHTML = `<i class="fas fa-check-circle mr-2"></i> <span>النصوص متطابقة تماماً</span>`;
            document.getElementById('errorsList').appendChild(checkDiv);
            document.getElementById('sourceTextReview').innerHTML = splitIntoLines(sourceText);
            document.getElementById('targetTextReview').innerHTML = splitIntoLines(targetText);
            document.getElementById('explanationText').innerHTML = `<p class="text-xl">النصوص متطابقة ولا يوجد اختلاف يجب الإشارة إليه.</p>`;
          } else {
            // تطبيق التظليل على النص المصدر فقط
            const sourceHighlighted = applyHighlights(sourceText, analysisOutput);
            document.getElementById('sourceTextReview').innerHTML = splitIntoLines(sourceHighlighted);
            // عرض النص الهدف بدون تعليم
            document.getElementById('targetTextReview').innerHTML = splitIntoLines(targetText);
            const explanationHTML = generateExplanation(sourceText, analysisOutput);
            document.getElementById('explanationText').innerHTML = explanationHTML;
          }
      
          // إظهار قسم التقرير وإدخال بيانات المترجم بعد التحليل
          document.getElementById('reportSection').classList.remove('hidden');
      
        } catch (error) {
          document.getElementById('errorsList').innerHTML = '';
          addError(`خطأ في التحليل: ${error.message}`);
        }
      });
      
      // مستمعي الأحداث لأزرار التقرير وإعادة المراجعة
      document.getElementById('downloadPdfBtn').addEventListener('click', downloadReportPDF);
      document.getElementById('downloadWordBtn').addEventListener('click', downloadReportWord);
      document.getElementById('reReviewBtn').addEventListener('click', reReview);
      
    })();
  </script>
</body>
</html>