File size: 47,959 Bytes
99ddd4c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import React, { useState, useEffect } from 'react';
import { 
  ArrowLeft, 
  BookOpen, 
  Sparkles, 
  Check, 
  X, 
  Search, 
  Award,
  HelpCircle,
  ExternalLink,
  Download,
  ChevronLeft,
  ChevronRight,
  ChevronsLeft,
  ChevronsRight,
  ZoomIn,
  ZoomOut,
  RotateCcw,
  FileText,
  PenTool,
  WifiOff,
  Wifi
} from 'lucide-react';
import { MURPHY_UNITS, MurphyUnit } from '../murphyData';

interface MurphyBookReaderProps {
  onAddHp?: (amount: number) => void;
  userHp?: number;
  userName?: string;
  onBack?: () => void;
  initialUnitId?: number;
  units?: MurphyUnit[];
  isKutubxona?: boolean;
  isOnline?: boolean;
}

export default function MurphyBookReader({ 
  onAddHp, 
  userHp = 0, 
  userName = "O'quvchi", 
  onBack, 
  initialUnitId, 
  units,
  isKutubxona = false,
  isOnline: propIsOnline
}: MurphyBookReaderProps) {
  const [localIsOnline, setLocalIsOnline] = useState<boolean>(() => typeof window !== "undefined" ? navigator.onLine : true);

  useEffect(() => {
    if (propIsOnline !== undefined) return;
    if (typeof window === "undefined") return;

    const handleOnline = () => setLocalIsOnline(true);
    const handleOffline = () => setLocalIsOnline(false);

    window.addEventListener("online", handleOnline);
    window.addEventListener("offline", handleOffline);

    return () => {
      window.removeEventListener("online", handleOnline);
      window.removeEventListener("offline", handleOffline);
    };
  }, [propIsOnline]);

  const isOnline = propIsOnline !== undefined ? propIsOnline : localIsOnline;

  const allUnits = units && units.length > 0 ? units : (isKutubxona ? [] : MURPHY_UNITS);
  const [selectedUnitId, setSelectedUnitId] = useState<number>(initialUnitId || allUnits[0]?.id || 1);
  const [searchTerm, setSearchTerm] = useState<string>("");
  const [quizAnswers, setQuizAnswers] = useState<{ [qId: number]: number }>({});
  const [quizChecked, setQuizChecked] = useState<boolean>(false);
  const [quizScore, setQuizScore] = useState<number>(0);
  const [quizFinished, setQuizFinished] = useState<boolean>(false);
  const [showExplanation, setShowExplanation] = useState<{ [qId: number]: boolean }>({});
  const [completedUnits, setCompletedUnits] = useState<number[]>([]);

  // πŸ“„ PREMIUM PDF READER & PAGINATION STATES
  const [activeTab, setActiveTab] = useState<'explanation' | 'pdf'>('explanation');
  const [pdfPage, setPdfPage] = useState<number>(1);
  const [pdfZoom, setPdfZoom] = useState<number>(100);
  const [pdfViewMode, setPdfViewMode] = useState<'scroll' | 'paginated'>('paginated');
  const [pdfViewerType, setPdfViewerType] = useState<'direct' | 'google'>('direct');

  // ✍️ Personal Student Notes for each specific book/unit
  const [studentNotes, setStudentNotes] = useState<{ [id: string]: string }>(() => {
    try {
      const stored = localStorage.getItem("bilimway_book_study_notes");
      return stored ? JSON.parse(stored) : {};
    } catch {
      return {};
    }
  });

  const saveStudentNotes = (id: string | number, text: string) => {
    const stringId = String(id);
    setStudentNotes(prev => {
      const updated = { ...prev, [stringId]: text };
      try {
        localStorage.setItem("bilimway_book_study_notes", JSON.stringify(updated));
      } catch (e) {
        console.error(e);
      }
      return updated;
    });
  };

  // ⭐ Study Reward mechanism (+50 HP)
  const [claimedBookHp, setClaimedBookHp] = useState<string[]>(() => {
    try {
      const stored = localStorage.getItem("bilimway_claimed_book_hp");
      return stored ? JSON.parse(stored) : [];
    } catch {
      return [];
    }
  });

  const claimReward = (id: string | number) => {
    const stringId = String(id);
    if (claimedBookHp.includes(stringId)) return;
    setClaimedBookHp(prev => {
      const updated = [...prev, stringId];
      try {
        localStorage.setItem("bilimway_claimed_book_hp", JSON.stringify(updated));
      } catch (e) {
        console.error(e);
      }
      return updated;
    });
    if (onAddHp) {
      onAddHp(50);
    }
  };

  // Sync activeTab whenever selectedUnitId changes
  useEffect(() => {
    const active = allUnits.find(u => u.id === selectedUnitId);
    if (active?.pdfUrl) {
      setActiveTab('pdf');
      setPdfPage(1); // reset to page 1 for new selected book
    } else {
      setActiveTab('explanation');
    }
  }, [selectedUnitId]);

  // Sound play helper
  const playBeep = (type: 'success' | 'fail' | 'move' | 'levelUp') => {
    try {
      const audioCtx = new (window.AudioContext || (window as any).webkitAudioContext)();
      const osc = audioCtx.createOscillator();
      const gain = audioCtx.createGain();
      
      osc.connect(gain);
      gain.connect(audioCtx.destination);
      
      if (type === 'success') {
        osc.frequency.setValueAtTime(587.33, audioCtx.currentTime); // D5
        osc.frequency.setValueAtTime(880, audioCtx.currentTime + 0.1); // A5
        gain.gain.setValueAtTime(0.1, audioCtx.currentTime);
        gain.gain.exponentialRampToValueAtTime(0.01, audioCtx.currentTime + 0.35);
        osc.start();
        osc.stop(audioCtx.currentTime + 0.35);
      } else if (type === 'fail') {
        osc.frequency.setValueAtTime(220, audioCtx.currentTime); // A3
        osc.frequency.setValueAtTime(147, audioCtx.currentTime + 0.15); // D3
        gain.gain.setValueAtTime(0.15, audioCtx.currentTime);
        gain.gain.exponentialRampToValueAtTime(0.01, audioCtx.currentTime + 0.4);
        osc.start();
        osc.stop(audioCtx.currentTime + 0.4);
      } else if (type === 'levelUp') {
        osc.frequency.setValueAtTime(523.25, audioCtx.currentTime); // C5
        osc.frequency.setValueAtTime(659.25, audioCtx.currentTime + 0.08); // E5
        osc.frequency.setValueAtTime(783.99, audioCtx.currentTime + 0.16); // G5
        osc.frequency.setValueAtTime(1046.50, audioCtx.currentTime + 0.24); // C6
        gain.gain.setValueAtTime(0.15, audioCtx.currentTime);
        gain.gain.exponentialRampToValueAtTime(0.01, audioCtx.currentTime + 0.5);
        osc.start();
        osc.stop(audioCtx.currentTime + 0.55);
      } else {
        osc.frequency.setValueAtTime(330, audioCtx.currentTime);
        gain.gain.setValueAtTime(0.05, audioCtx.currentTime);
        gain.gain.exponentialRampToValueAtTime(0.01, audioCtx.currentTime + 0.1);
        osc.start();
        osc.stop(audioCtx.currentTime + 0.1);
      }
    } catch (e) {
      console.log("Audio not supported yet", e);
    }
  };

  const activeUnit = allUnits.find(u => u.id === selectedUnitId) || allUnits[0] || MURPHY_UNITS[0];

  const handleSelectUnit = (unitId: number) => {
    setSelectedUnitId(unitId);
    setQuizAnswers({});
    setQuizChecked(false);
    setQuizScore(0);
    setQuizFinished(false);
    setShowExplanation({});
    playBeep('move');
  };

  const handleSelectOption = (qId: number, optionIdx: number) => {
    if (quizChecked) return;
    setQuizAnswers(prev => ({ ...prev, [qId]: optionIdx }));
    playBeep('move');
  };

  const handleCheckQuiz = () => {
    let score = 0;
    (activeUnit.questions || []).forEach(q => {
      if (quizAnswers[q.id] === q.correctIndex) {
        score += 1;
      }
    });
    setQuizScore(score);
    setQuizChecked(true);

    if (score === (activeUnit.questions || []).length) {
      setQuizFinished(true);
      if (!completedUnits.includes(activeUnit.id)) {
        setCompletedUnits(prev => [...prev, activeUnit.id]);
        if (onAddHp) {
          onAddHp(25);
        }
      }
      playBeep('levelUp');
    } else if (score >= (activeUnit.questions || []).length * 0.5) {
      playBeep('success');
    } else {
      playBeep('fail');
    }
  };

  const handleResetQuiz = () => {
    setQuizAnswers({});
    setQuizChecked(false);
    setQuizScore(0);
    setQuizFinished(false);
    setShowExplanation({});
    playBeep('move');
  };

  const handleDownloadUnit = () => {
    if (!activeUnit) return;
    try {
      const examplesContent = (activeUnit.examples || []).map((ex: any, idx: number) => {
        return `${idx + 1}. ING: "${ex.original}"\n   UZB:  "${ex.translationUz || ex.translation || ''}"`;
      }).join('\n\n');

      const fileText = `=====================================================
            KUTUBXONA DARSLIGI YUKLAMASI
=====================================================
Mavzu (Sarlavha): ${activeUnit.title}
Unit Tartib Raqami: ${activeUnit.id}
Tavsif (Mavzu): ${activeUnit.topicUz || 'Kiritilmagan'}

-----------------------------------------------------
[INGLIZCHA ESLATMALAR / ENGLISH NOTES]
${activeUnit.explanationEn || 'No notes available.'}

-----------------------------------------------------
[O'ZBEKCHA SHARH / TUSHUNTIRISH]
${activeUnit.explanationUz || 'Izohlar kiritilmagan.'}

-----------------------------------------------------
[AMALIY MISOLLAR / BILINGUAL EXAMPLES]
${examplesContent || 'Misollar kiritilmagan.'}

-----------------------------------------------------
Ushbu darslik materiali BilimWay Kutubxonasi tomonidan taqdim etildi.
Yuklab olingan vaqt: ${new Date().toLocaleString()}
Web-manzil: ${window.location.origin}
=====================================================`;

      const blob = new Blob([fileText], { type: 'text/plain;charset=utf-8' });
      const url = URL.createObjectURL(blob);
      const link = document.createElement('a');
      link.href = url;
      link.download = `BilimWay_Kutubxona_Unit_${activeUnit.id}_${activeUnit.title.replace(/[^a-z0-9_-]/gi, '_')}.txt`;
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      URL.revokeObjectURL(url);
      
      playBeep('success');
    } catch (e) {
      console.warn("Kitob yuklab olishda xatolik:", e);
      alert("Havola orqali yuklab olishda muammo kutilmoqda.");
    }
  };

  const filteredUnits = allUnits.filter(u => 
    u.title.toLowerCase().includes(searchTerm.toLowerCase()) || 
    u.topicUz.toLowerCase().includes(searchTerm.toLowerCase())
  );

  return (
    <div className="h-screen w-screen bg-[#1c1212] text-slate-100 flex flex-col font-sans overflow-hidden select-none">
      
      {/* HEADER */}
      <header className="bg-[#2a1b1b] border-b border-[#3d2828] px-6 py-4 flex flex-col md:flex-row justify-between items-center gap-4 z-10 shadow-lg">
        <div className="flex items-center gap-4">
          <button 
            onClick={() => {
              playBeep('move');
              if (onBack) {
                onBack();
              } else {
                window.close();
                window.location.href = window.location.origin;
              }
            }}
            className="flex items-center gap-2 px-3 py-1.5 bg-[#402a2a] hover:bg-[#523535] border border-[#523535] rounded-xl text-xs font-bold text-[#f7a3a3] hover:text-white transition cursor-pointer"
          >
            <ArrowLeft className="w-4 h-4" />
            <span>Kutubxonadan Chiqish</span>
          </button>
          
          <div className="h-6 w-px bg-[#3d2828]" />
          
          <div className="flex items-center gap-2">
            <span className="text-xl">πŸ“š</span>
            <div>
              <h1 className="text-base md:text-lg font-display font-semibold text-white tracking-tight flex flex-wrap items-center gap-2">
                {isKutubxona ? "KUTUBXONA" : "Essential Grammar in Use"}
                <span className="text-[10px] bg-red-600/25 text-red-300 border border-red-500/40 px-2 py-0.5 rounded-full font-mono font-extrabold uppercase">
                  {isKutubxona ? "Real-Time" : "4th Edition"}
                </span>
                {!isOnline && (
                  <span className="text-[10px] bg-amber-950/90 text-amber-300 border border-amber-500/40 px-1.5 py-0.5 rounded-full font-mono font-extrabold flex items-center gap-1 uppercase animate-pulse">
                    <WifiOff className="w-2.5 h-2.5 text-amber-400" /> Offline Kesh
                  </span>
                )}
              </h1>
              <p className="text-[10px] md:text-xs text-slate-400">
                {isKutubxona ? "Admin yuklagan maxsus darsliklar va kitoblar" : "Raymond Murphy β€’ Interaktiv Bilingual Nashr"}
              </p>
            </div>
          </div>
        </div>

        <div className="flex items-center gap-4 bg-[#1c1212]/55 border border-[#402a2a] px-3.5 py-1.5 rounded-2xl">
          <div className="flex flex-col text-right">
            <span className="text-xs font-mono text-[#fca5a5]">O'quvchi: <strong>{userName}</strong></span>
            <span className="text-[10px] text-slate-400">Kitoblar: {allUnits.length} ta darslik ({userHp} HP)</span>
          </div>
          <div className="w-9 h-9 rounded-xl bg-red-600/15 border border-red-500/30 flex justify-center items-center text-red-400 font-bold text-sm">
            πŸ“–
          </div>
        </div>
      </header>

      {/* CORE BODY GRID */}
      <div className="flex-1 flex overflow-hidden">
        
        {/* LEFT INDEX BAR */}
        <aside className="w-80 border-r border-[#3d2828] bg-[#221616] flex flex-col hidden lg:flex">
          {/* SEARCH BAR */}
          <div className="p-4 border-b border-[#3d2828] flex flex-col gap-2.5">
            <span className="text-[10px] font-bold text-[#fca5a5] uppercase tracking-wider font-mono">
              {isKutubxona ? "Yuklangan Kitoblar" : "Darslik Mundarijasi"}
            </span>
            <div className="relative">
              <input 
                type="text" 
                value={searchTerm}
                onChange={(e) => setSearchTerm(e.target.value)}
                placeholder="Kitoblarni qidirish..."
                className="w-full bg-[#170e0e] border border-[#402a2a] pl-9.5 pr-4 py-2 rounded-xl text-xs text-white placeholder-slate-500 focus:outline-none focus:border-red-500 focus:ring-1 focus:ring-red-500 font-sans"
              />
              <Search className="w-4 h-4 text-slate-500 absolute left-3 top-2.5" />
            </div>
          </div>

          {/* LIST CONTAINER */}
          <div className="flex-1 overflow-y-auto p-3 space-y-2 scroller-red">
            {filteredUnits.map((u) => {
              const isActive = u.id === selectedUnitId;
              return (
                <button
                  key={u.id}
                  onClick={() => handleSelectUnit(u.id)}
                  className={`w-full text-left p-3.5 rounded-xl transition duration-200 border cursor-pointer hover:shadow-md ${
                    isActive 
                      ? 'bg-red-950/40 border-red-500/60 shadow-lg shadow-red-500/5 text-white' 
                      : 'bg-[#1a0f0f]/40 border-[#331f1f] hover:bg-[#2e1d1d]/30 hover:border-[#4d2f2f]'
                  }`}
                >
                  <div className="flex justify-between items-start mb-1.5">
                    <span className="text-[9px] font-bold font-mono text-[#fca5a5] tracking-wider uppercase">Unit {u.id}</span>
                  </div>
                  <h4 className={`text-xs font-semibold leading-relaxed ${isActive ? 'text-white' : 'text-slate-200'}`}>
                    {u.title}
                  </h4>
                  <p className="text-[10px] text-slate-400 mt-1 italic truncate max-w-[240px]">
                    {u.topicUz}
                  </p>
                </button>
              );
            })}
            {filteredUnits.length === 0 && (
              <div className="text-center py-12 text-slate-500 text-xs">
                Ushbu bo'limda hali kitob yuklanmagan.
              </div>
            )}
          </div>
        </aside>
         {/* CENTER SPLIT PAGES CONTROLS AND CONTENT VIEW */}
        <main className="flex-1 flex flex-col bg-[#170f0f] overflow-y-auto p-4 md:p-8">
          
          {!isOnline && (
            <div id="offline_reader_notice" className="max-w-6xl mx-auto w-full mb-6 bg-amber-950/40 border border-amber-500/20 rounded-2xl p-4 flex flex-col sm:flex-row items-start sm:items-center justify-between gap-3 animate-fade-in">
              <div className="flex items-center gap-3">
                <div className="p-2 bg-amber-500/15 rounded-xl text-amber-400">
                  <WifiOff className="w-4 h-4 animate-pulse" />
                </div>
                <div>
                  <h4 className="text-xs font-bold text-amber-200">Oflayn Rejim Faol</h4>
                  <p className="text-[11px] text-slate-300">Ushbu kitob va uning amaliy mashqlari keshdan yuklangan va to'liq oflayn ishlaydi.</p>
                </div>
              </div>
              <span className="text-[9px] bg-amber-500/20 text-amber-300 border border-amber-500/30 px-2 py-0.5 rounded-full font-mono font-bold tracking-wider uppercase flex-shrink-0 self-start sm:self-center">
                Keşlash Faol ⚑
              </span>
            </div>
          )}
          
          {/* TABS SELECTOR IF PDF EXISTS */}
          {activeUnit?.pdfUrl && (
            <div className="max-w-6xl mx-auto w-full mb-6 bg-[#2a1b1b] p-1.5 rounded-2xl border border-[#3d2828] flex gap-2">
              <button
                onClick={() => { playBeep('move'); setActiveTab('explanation'); }}
                className={`flex-1 py-3 px-4 rounded-xl text-xs font-bold font-mono transition flex items-center justify-center gap-2 cursor-pointer ${
                  activeTab === 'explanation' 
                    ? 'bg-red-650 text-white shadow-xl font-black' 
                    : 'text-slate-400 hover:text-slate-200'
                }`}
              >
                <BookOpen className="w-4 h-4" />
                <span>Mavzu Tafsilotlari πŸ“‘</span>
              </button>
              <button
                onClick={() => { playBeep('move'); setActiveTab('pdf'); }}
                className={`flex-1 py-3 px-4 rounded-xl text-xs font-bold font-mono transition flex items-center justify-center gap-2 cursor-pointer ${
                  activeTab === 'pdf' 
                    ? 'bg-red-650 text-white shadow-xl font-black' 
                    : 'text-slate-400 hover:text-slate-200'
                }`}
              >
                <FileText className="w-4 h-4 text-white" />
                <span className="flex items-center gap-1.5">
                  PDF Mutolaa Zali <span className="text-[10px] bg-red-800 border border-red-500 text-white px-1.5 py-0.2 rounded uppercase animate-pulse">Paginated</span>
                </span>
              </button>
            </div>
          )}

          {activeTab === 'pdf' && activeUnit?.pdfUrl ? (
            /* BRAND NEW IMMERSIVE INTERACTIVE PDF READER VIEW WITH ADVANCED PAGINATION */
            <div className="max-w-6xl mx-auto w-full flex flex-col lg:flex-row gap-6 items-start pb-12 animate-fade-in text-white select-none">
              
              {/* Left Column: Interactive PDF Canvas Viewport with Paginating overlay */}
              <div className="flex-1 w-full bg-[#241717] border border-[#402a2a] p-4 md:p-6 rounded-3xl shadow-2xl flex flex-col gap-4 min-h-[500px] lg:min-h-[720px]">
                
                {/* Header Actions */}
                <div className="flex flex-wrap items-center justify-between gap-3 border-b border-[#3d2828] pb-3.5">
                  <div className="flex items-center gap-2">
                    <span className="w-2.5 h-2.5 rounded-full bg-red-500 animate-ping" />
                    <span className="text-[10px] font-bold text-red-400 tracking-widest font-mono uppercase">Ilova ichida o'quvchi</span>
                  </div>
                  
                  {/* Mode Selector & Engine Toggles */}
                  <div className="flex flex-wrap items-center gap-2 text-xs">
                    
                    {/* View Engine Toggle */}
                    <div className="flex items-center bg-[#1c1212] p-1 rounded-xl border border-[#382323]">
                      <button
                        onClick={() => { playBeep('move'); setPdfViewerType('direct'); }}
                        className={`px-3 py-1.5 rounded-lg text-[9.5px] font-bold font-mono transition cursor-pointer ${
                          pdfViewerType === 'direct' 
                            ? 'bg-red-600 text-white shadow' 
                            : 'text-slate-400 hover:text-slate-200'
                        }`}
                      >
                        Nativ
                      </button>
                      <button
                        onClick={() => { playBeep('move'); setPdfViewerType('google'); }}
                        className={`px-3 py-1.5 rounded-lg text-[9.5px] font-bold font-mono transition cursor-pointer ${
                          pdfViewerType === 'google' 
                            ? 'bg-red-600 text-white shadow' 
                            : 'text-slate-400 hover:text-slate-200'
                        }`}
                      >
                        Google
                      </button>
                    </div>

                    {/* View Mode Toggle: Scroll vs Paginated */}
                    <div className="flex items-center bg-[#1c1212] p-1 rounded-xl border border-[#382323]">
                      <button
                        onClick={() => { playBeep('move'); setPdfViewMode('paginated'); }}
                        className={`px-3 py-1.5 rounded-lg text-[9.5px] font-bold font-mono transition flex items-center gap-1 cursor-pointer ${
                          pdfViewMode === 'paginated' 
                            ? 'bg-red-600 text-white shadow' 
                            : 'text-slate-400 hover:text-slate-200'
                        }`}
                      >
                        <span>πŸ“– Sahifali</span>
                      </button>
                      <button
                        onClick={() => { playBeep('move'); setPdfViewMode('scroll'); }}
                        className={`px-3 py-1.5 rounded-lg text-[9.5px] font-bold font-mono transition flex items-center gap-1 cursor-pointer ${
                          pdfViewMode === 'scroll' 
                            ? 'bg-red-600 text-white shadow' 
                            : 'text-slate-400 hover:text-slate-200'
                        }`}
                      >
                        <span>πŸ“œ To'liq</span>
                      </button>
                    </div>

                    {/* Zoom actions */}
                    <div className="flex items-center gap-1 bg-[#1c1212] p-1 rounded-xl border border-[#382323]">
                      <button 
                        onClick={() => setPdfZoom(prev => Math.max(50, prev - 10))}
                        className="p-1 hover:text-white text-slate-400 cursor-pointer"
                        title="Kichraytirish"
                      >
                        <ZoomOut className="w-3.5 h-3.5" />
                      </button>
                      <span className="text-[10px] font-mono text-slate-300 px-1 font-bold">{pdfZoom}%</span>
                      <button 
                        onClick={() => setPdfZoom(prev => Math.min(200, prev + 10))}
                        className="p-1 hover:text-white text-slate-400 cursor-pointer"
                        title="Kattalashtirish"
                      >
                        <ZoomIn className="w-3.5 h-3.5" />
                      </button>
                      <button 
                        onClick={() => setPdfZoom(100)}
                        className="p-0.5 ml-1 text-slate-500 hover:text-slate-300 cursor-pointer"
                        title="Asliga qaytarish"
                      >
                        <RotateCcw className="w-3 h-3" />
                      </button>
                    </div>

                  </div>
                </div>

                {/* Standard PDF Paginator Bar */}
                {pdfViewMode === 'paginated' && (
                  <div className="bg-[#1c1212] border border-[#3d2828] p-3 rounded-2xl flex flex-col sm:flex-row items-center justify-between gap-3 shadow-md">
                    
                    {/* Buttons & Number Selector */}
                    <div className="flex flex-wrap items-center gap-2">
                      <button
                        onClick={() => { playBeep('move'); setPdfPage(1); }}
                        disabled={pdfPage <= 1}
                        className="p-2 rounded-xl bg-[#311f1f] border border-[#503232] disabled:opacity-30 disabled:cursor-not-allowed hover:bg-[#452b2b] text-slate-200 transition cursor-pointer"
                        title="Birinchi sahifa"
                      >
                        <ChevronsLeft className="w-4 h-4" />
                      </button>
                      <button
                        onClick={() => { playBeep('move'); setPdfPage(prev => Math.max(1, prev - 1)); }}
                        disabled={pdfPage <= 1}
                        className="p-2 rounded-xl bg-[#311f1f] border border-[#503232] disabled:opacity-30 disabled:cursor-not-allowed hover:bg-[#452b2b] text-slate-200 transition font-bold text-xs flex items-center gap-1 cursor-pointer"
                      >
                        <ChevronLeft className="w-4 h-4" />
                        <span>Oldingi</span>
                      </button>
                      
                      {/* Active Input selector */}
                      <div className="flex items-center gap-1 mx-2">
                        <span className="text-xs text-slate-400 font-mono">Sahifa</span>
                        <input
                          type="number"
                          min="1"
                          max="100"
                          value={pdfPage}
                          onChange={(e) => {
                            const val = parseInt(e.target.value);
                            if (val && val > 0) setPdfPage(val);
                          }}
                          className="w-12 bg-black border border-[#503232] text-white py-1 text-center font-mono font-bold text-xs rounded-lg focus:outline-none focus:border-red-500 font-bold"
                        />
                        <span className="text-xs text-slate-500 font-mono">/ 50-gacha</span>
                      </div>

                      <button
                        onClick={() => { playBeep('move'); setPdfPage(prev => prev + 1); }}
                        className="p-2 rounded-xl bg-[#311f1f] border border-[#503232] hover:bg-[#452b2b] text-slate-200 transition font-bold text-xs flex items-center gap-1 cursor-pointer"
                      >
                        <span>Keyingi</span>
                        <ChevronRight className="w-4 h-4" />
                      </button>
                      
                      <button
                        onClick={() => { playBeep('move'); setPdfPage(10); }}
                        className="p-2 rounded-xl bg-[#311f1f] border border-[#503232] hover:bg-[#452b2b] text-slate-200 transition cursor-pointer font-bold text-xs"
                        title="Jump to 10"
                      >
                        10 ⚑
                      </button>
                      <button
                        onClick={() => { playBeep('move'); setPdfPage(20); }}
                        className="p-2 rounded-xl bg-[#311f1f] border border-[#503232] hover:bg-[#452b2b] text-slate-200 transition cursor-pointer font-bold text-xs"
                        title="Jump to 20"
                      >
                        20 ⚑
                      </button>
                    </div>

                    {/* Smooth Range Slider for rapid page scrub */}
                    <div className="w-full sm:w-44 flex items-center gap-2">
                      <span className="text-[10px] text-slate-500 font-mono font-bold">SLAYDER:</span>
                      <input 
                        type="range"
                        min="1"
                        max="50"
                        value={pdfPage}
                        onChange={(e) => setPdfPage(parseInt(e.target.value))}
                        className="flex-1 accent-red-650 h-1 bg-slate-950 rounded-lg appearance-none cursor-pointer"
                      />
                    </div>

                  </div>
                )}

                {/* PDF rendering viewport frame wrapper */}
                <div className="flex-1 bg-white border border-[#3a2525] rounded-2xl relative overflow-hidden min-h-[480px] lg:min-h-[600px] flex flex-col">
                  {/* Native scroll page tracking indicator when scroll view is active */}
                  {pdfViewMode === 'scroll' && (
                    <div className="absolute top-2.5 left-2.5 bg-black/80 border border-red-500/20 text-[9.5px] text-white px-2.5 py-1 rounded-md font-mono z-10 select-none backdrop-blur animate-fade-in flex items-center gap-1.5">
                      <span className="w-1.5 h-1.5 rounded bg-orange-400 animate-pulse" />
                      Avto-sahifalash: barcha sahifalar ketma-ket
                    </div>
                  )}

                  {/* PDF embed viewport */}
                  <div className="w-full h-full flex-1 relative bg-white" style={{ transform: `scale(${pdfZoom / 100})`, transformOrigin: 'top center', transition: 'transform 0.2s ease-in-out' }}>
                    <iframe
                      key={`${activeUnit?.id}-${pdfViewMode}-${pdfViewerType}-${pdfPage}`}
                      src={pdfViewerType === 'direct' 
                        ? (pdfViewMode === 'paginated' ? `${activeUnit?.pdfUrl}#page=${pdfPage}` : activeUnit?.pdfUrl)
                        : (pdfViewMode === 'paginated' 
                            ? `https://docs.google.com/gview?url=${encodeURIComponent(activeUnit?.pdfUrl || '')}&embedded=true#page=${pdfPage}` 
                            : `https://docs.google.com/gview?url=${encodeURIComponent(activeUnit?.pdfUrl || '')}&embedded=true`
                          )
                      }
                      className="w-full h-full border-0 absolute inset-0 bg-white"
                      loading="lazy"
                    />
                  </div>
                </div>

                {/* Helpful prompt */}
                <div className="text-[11px] text-slate-300 flex flex-col md:flex-row md:items-center justify-between gap-4 bg-[#2b1717] p-3.5 rounded-2xl border border-red-500/20 shadow-lg animate-fade-in">
                  <div className="flex items-start gap-2.5">
                    <span className="text-base">πŸ’‘</span>
                    <span className="leading-relaxed">
                      <strong>Darslik yuklanishida muammo bo'lsa yoki ekran qorayib qolsa:</strong> Microsoft Edge, Safari va ba'zi brauzerlar xavfsizlik cheklovlari tufayli PDF-ni bloklashi mumkin. Muammoni bartaraf qilish uchun quyidagi tugmani bosing:
                    </span>
                  </div>
                  <a 
                    href={activeUnit?.pdfUrl} 
                    target="_blank" 
                    rel="noopener noreferrer" 
                    className="bg-red-650 hover:bg-red-550 text-white font-extrabold py-2.5 px-4 rounded-xl text-xs transition duration-200 flex items-center justify-center gap-1.5 shadow-md flex-shrink-0 animate-pulse text-center uppercase tracking-wider font-mono cursor-pointer"
                  >
                    <span>Yangi oynada ochish πŸš€</span>
                    <ExternalLink className="w-3.5 h-3.5" />
                  </a>
                </div>

              </div>

              {/* Right Column: Interaction sidebar (Study reward and vocabulary organizer) */}
              <div className="w-full lg:w-80 flex flex-col gap-5 select-none self-stretch">
                
                {/* Visual Metadata card */}
                <div className="bg-[#241717] border border-[#402a2a] p-4.5 rounded-3xl flex flex-col gap-2 relative overflow-hidden">
                  <span className="text-[10px] bg-red-600/10 border border-red-500/20 text-red-300 font-mono font-bold px-2 py-0.5 rounded uppercase self-start leading-none">
                    Kitob Tafsilotlari πŸ“–
                  </span>
                  <h4 className="text-xs font-bold text-white mt-1 line-clamp-2 leading-snug">
                    {activeUnit?.title}
                  </h4>
                  <p className="text-[11px] text-slate-400 italic mt-0.5">
                    ✍️ Muallif: {activeUnit?.author || "Noma'lum"}
                  </p>
                  <p className="text-xs text-slate-400 italic mt-1.5 leading-relaxed">
                    Ushbu darslikni faol o'rganish sizga chuqur bilim va qo'shimcha rag'bat taqdim etadi.
                  </p>
                </div>

                {/* Gamified study reward card */}
                <div className="bg-gradient-to-br from-[#2a1717] to-[#1c1212] border border-[#4d2c2c] p-5 rounded-3xl flex flex-col gap-3.5 shadow-xl">
                  <div className="flex items-center gap-3">
                    <div className="w-9 h-9 bg-red-500/10 rounded-xl flex items-center justify-center text-red-400 text-lg">
                      ⭐
                    </div>
                    <div>
                      <h4 className="text-xs font-bold text-white">Mutolaa mukofoti</h4>
                      <p className="text-[10px] text-slate-400">Kitob darsliklarini to'liq o'qib +50 HP to'plang</p>
                    </div>
                  </div>

                  {claimedBookHp.includes(String(activeUnit?.id)) ? (
                    <div className="bg-emerald-950/30 border border-emerald-500/30 text-emerald-400 text-xs font-mono p-3 rounded-xl text-center font-bold flex items-center justify-center gap-1.5 animate-fade-in">
                      <Check className="w-4 h-4" /> 50 HP Hisobingizga qo'shildi βœ”
                    </div>
                  ) : (
                    <button
                      onClick={() => {
                        playBeep('levelUp');
                        if (activeUnit) {
                          claimReward(activeUnit.id);
                        }
                      }}
                      className="w-full bg-gradient-to-r from-emerald-600 to-teal-655 text-white font-mono font-extrabold py-3 px-4 rounded-xl text-xs tracking-wider transition uppercase hover:from-emerald-555 hover:shadow-lg shadow-emerald-950/20 flex items-center justify-center gap-1 cursor-pointer"
                    >
                      πŸ“– DARS TAHLILINI O'QIDIM (+50 HP)
                    </button>
                  )}
                </div>

                {/* Annotation pad sidebar */}
                <div className="bg-[#241717] border border-[#402a2a] p-5 rounded-3xl flex flex-col gap-3 flex-1">
                  <div className="flex justify-between items-center border-b border-[#3d2828] pb-2">
                    <div className="flex items-center gap-1.5 text-xs text-white font-bold">
                      <PenTool className="w-4 h-4 text-red-400" />
                      <span>Shaxsiy eslatmalar</span>
                    </div>
                    <span className="text-[9.5px] text-slate-500 font-mono uppercase">Avto-saqlash</span>
                  </div>

                  <p className="text-[10px] text-slate-400 leading-snug">
                    Mutolaa davomida o'rgangan inglizcha frazalaringiz, so'zlar yoki murakkab qoidalarni yozib boring:
                  </p>

                  <textarea 
                    value={(activeUnit && studentNotes[String(activeUnit.id)]) || ""}
                    onChange={(e) => {
                      if (activeUnit) {
                        saveStudentNotes(activeUnit.id, e.target.value);
                      }
                    }}
                    placeholder="Masalan: 1. am/is/are - subject markerlar... (Yozuvlar avtomatik saqlanib qoladi)"
                    className="w-full h-80 bg-[#1c1212] border border-[#3e2727] p-3 text-xs text-slate-200 placeholder-slate-600 rounded-xl focus:outline-none focus:border-red-500 focus:ring-1 focus:ring-red-500 leading-relaxed font-sans scrollbar-thin flex-1 select-text scrollbar-track-transparent scrollbar-thumb-stone-800"
                  />
                </div>

              </div>

            </div>
          ) : (
            <div className={`max-w-6xl mx-auto w-full ${isKutubxona ? 'flex flex-col max-w-3xl' : 'grid grid-cols-1 xl:grid-cols-2'} gap-8 items-start my-auto pb-12`}>
              
              {/* LEFT PAGE: GRAMMAR RULES AND EXPLANATIONS */}
              <section className="bg-[#241717] border border-[#402a2a] p-5 md:p-7 rounded-3xl shadow-2xl relative overflow-hidden flex flex-col gap-6 w-full">
                <div className="absolute top-0 right-0 w-32 h-32 bg-red-600/5 rounded-full blur-3xl" />
                
                {/* HEADER DISPLAY WITH STUNNING ACCENTS */}
                <div className="border-b border-[#3d2828] pb-4 flex justify-between items-start gap-4">
                  <div>
                    <span className="text-xs font-bold text-red-400 tracking-widest font-mono uppercase">Kitob Mutolaasi</span>
                    <h2 className="text-xl md:text-2xl font-display font-bold text-white mt-1">
                      {activeUnit ? activeUnit.title : "Sarlavhasiz darslik"}
                    </h2>
                    <p className="text-xs text-[#fca5a5] mt-1 font-medium bg-red-600/5 inline-block px-2.5 py-1 rounded-lg border border-red-500/10">
                      Mavzu: <strong>{activeUnit ? activeUnit.topicUz : ""}</strong>
                    </p>
                  </div>
                  
                  {/* PDF/TXT DOWNLOAD BUTTON FOR USER COMPLIANCE */}
                  <button
                    onClick={handleDownloadUnit}
                    className="bg-red-600 hover:bg-red-500 text-white text-xs font-bold py-2 px-3.5 rounded-xl flex items-center gap-1.5 transition-colors cursor-pointer border border-red-500/20 shadow-md flex-shrink-0"
                  >
                    <Download className="w-4 h-4" />
                    <span className="hidden sm:inline">Kitobni Yuklab Olish</span>
                    <span className="sm:hidden">Yuklash</span>
                  </button>
                </div>

                {/* SECTION: ENGLISH EXPLANATION */}
                {activeUnit?.explanationEn && (
                  <div>
                    <span className="text-[10px] bg-red-600/15 text-red-300 font-bold border border-red-500/20 px-2.5 py-1 rounded-md uppercase tracking-wider font-mono">
                      English Notes / Notes
                    </span>
                    <p className="text-xs md:text-sm text-slate-200 leading-relaxed mt-2.5 pl-1 italic">
                      "{activeUnit.explanationEn}"
                    </p>
                  </div>
                )}

                {/* SECTION: UZBEK TRANSLATION EXPLANATION */}
                {activeUnit?.explanationUz && (
                  <div className="bg-[#1c1212] border border-[#3d2828] p-4 rounded-2xl relative">
                    <span className="text-[10px] bg-slate-850 text-slate-300 font-bold border border-[#402a2a] px-2.5 py-1 rounded-md uppercase tracking-wider font-mono">
                      O'zbekcha Tushuntirish
                    </span>
                    <p className="text-xs md:text-sm text-slate-300 leading-relaxed mt-3 whitespace-pre-line font-sans">
                      {activeUnit.explanationUz}
                    </p>
                  </div>
                )}

                {/* SECTION: EXAMPLES CARDS PAIRINGS */}
                {activeUnit?.examples && activeUnit.examples.length > 0 && (
                  <div className="flex flex-col gap-3">
                    <span className="text-[10px] text-slate-400 font-bold tracking-wider uppercase font-mono pl-1">Examples / Misollar:</span>
                    <div className="grid grid-cols-1 gap-3">
                      {activeUnit.examples.map((ex: any, idx: number) => (
                        <div key={idx} className="bg-[#1c1212]/50 border border-[#382323] p-3 rounded-xl flex gap-3 transition hover:bg-[#1c1212]">
                          <div className="w-5 h-5 rounded-full bg-red-500/15 border border-red-500/30 flex justify-center items-center text-[10px] font-bold text-red-400 font-mono flex-shrink-0">
                            {idx + 1}
                          </div>
                          <div className="text-xs md:text-sm">
                            <p className="text-white font-mono italic">"{ex.original}"</p>
                            <p className="text-slate-400 mt-1">"{ex.translationUz || ex.translation || ''}"</p>
                          </div>
                        </div>
                      ))}
                    </div>
                  </div>
                )}
              </section>

              {/* RIGHT PAGE: THE EXERCISES AND LIVE QUIZ - HIDDEN IN KUTUBXONA MODE */}
              {!isKutubxona && (
                <section className="bg-[#241717] border border-[#402a2a] p-5 md:p-7 rounded-3xl shadow-2xl relative flex flex-col gap-6 w-full">
                  <div className="absolute top-0 right-0 w-32 h-32 bg-emerald-600/5 rounded-full blur-3xl" />
                  
                  {/* HEADER */}
                  <div className="border-b border-[#3d2828] pb-4 flex justify-between items-center">
                    <div>
                      <span className="text-xs font-bold text-emerald-400 tracking-widest font-mono uppercase">Interactive Exercises</span>
                      <h3 className="text-lg font-display font-semibold text-white mt-0.5">
                        Unit {activeUnit?.id} Mashqlari
                      </h3>
                    </div>
                    {quizChecked && (
                      <span className="text-xs bg-emerald-500/10 border border-emerald-500/25 px-3 py-1 rounded-full font-bold text-emerald-400">
                        NATIJA: {quizScore} / {activeUnit?.questions?.length || 0}
                      </span>
                    )}
                  </div>

                  {/* QUESTIONS */}
                  <div className="flex flex-col gap-5">
                    {(activeUnit?.questions || []).map((q: any, qIdx: number) => {
                      const selectedOpt = quizAnswers[q.id];
                      const isCorrect = selectedOpt === q.correctIndex;
                      const showExp = showExplanation[q.id];

                      return (
                        <div key={q.id} className="bg-[#1c1212] border border-[#3a2525] p-4.5 rounded-2xl flex flex-col gap-3.5 relative">
                          <div className="flex justify-between items-start gap-2">
                            <span className="text-[10px] font-mono text-slate-500 font-bold uppercase">Mashq #{qIdx + 1}</span>
                          </div>
                          
                          <p className="text-xs md:text-sm font-semibold text-slate-205 leading-relaxed font-mono">
                            {q.sentence}
                          </p>
                          
                          <div className="grid grid-cols-1 gap-2 mt-1">
                            {q.options.map((opt: string, optIdx: number) => {
                              const isChosenByMe = selectedOpt === optIdx;
                              return (
                                <button
                                  key={optIdx}
                                  disabled={quizChecked}
                                  onClick={() => handleSelectOption(q.id, optIdx)}
                                  className={`text-left p-3 rounded-xl text-xs font-mono transition-all duration-200 cursor-pointer ${
                                    isChosenByMe 
                                      ? 'bg-red-500/10 text-red-400 border border-red-500/30 font-bold' 
                                      : 'bg-[#241717] hover:bg-[#2b1c1c] text-slate-300 border border-[#382323]'
                                  }`}
                                >
                                  {opt}
                                </button>
                              );
                            })}
                          </div>

                          {quizChecked && (
                            <div className="border-t border-[#3a2525]/50 pt-2.5 mt-1">
                              <div className="flex items-center justify-between">
                                <span className={`font-bold flex items-center gap-1 text-xs ${isCorrect ? 'text-emerald-400' : 'text-red-400'}`}>
                                  {isCorrect ? <Check className="w-3.5 h-3.5" /> : <X className="w-3.5 h-3.5" />}
                                  {isCorrect ? "To'g'ri javob!" : "Noto'g'ri javob!"}
                                </span>
                                <button 
                                  onClick={() => setShowExplanation(prev => ({ ...prev, [q.id]: !showExp }))}
                                  className="text-slate-400 hover:text-white flex items-center gap-1 text-xs cursor-pointer"
                                >
                                  <HelpCircle className="w-3.5 h-3.5" /> Tahlili
                                </button>
                              </div>
                              
                              {showExp && (
                                <div className="bg-[#170e0e] border border-red-500/15 p-2.5 rounded-lg text-[11px] text-slate-300 leading-relaxed font-sans mt-2 animate-fade-in">
                                  <strong>Tushuntirish:</strong> {q.hint || "Qoida tushuntirishi kiritilmagan."}
                                </div>
                              )}
                            </div>
                          )}
                        </div>
                      );
                    })}
                  </div>

                  {/* ACTION BUTTON CONTAINER */}
                  <div className="border-t border-[#3d2828] pt-5 flex items-center justify-between gap-4">
                    {!quizChecked ? (
                      <button
                        onClick={handleCheckQuiz}
                        disabled={(activeUnit?.questions || []).some((q: any) => quizAnswers[q.id] === undefined)}
                        className="w-full bg-[#cc3333] hover:bg-red-600 disabled:opacity-40 text-white font-bold py-3 px-4 rounded-xl shadow-lg hover:shadow-red-655/15 transition-all text-sm font-mono flex items-center justify-center gap-1.5 cursor-pointer disabled:cursor-not-allowed"
                      >
                        <span>Mashqni Tekshirish βœ“</span>
                      </button>
                    ) : (
                      <div className="flex gap-3 w-full">
                        <button
                          onClick={handleResetQuiz}
                          className="w-full bg-[#3d2828] hover:bg-[#4d3232] border border-[#5c3c3c] text-slate-300 font-bold py-3 px-4 rounded-xl transition cursor-pointer text-sm font-mono text-center flex items-center justify-center"
                        >
                          <span>Qayta urinish ⟲</span>
                        </button>
                        {quizFinished && (
                          <div className="w-full bg-emerald-500/10 border border-emerald-500/30 rounded-xl p-1 flex justify-center items-center font-bold text-xs text-emerald-400 font-mono text-center animate-pulse">
                            ⭐ 100% Correct +25 HP Added!
                          </div>
                        )}
                      </div>
                    )}
                  </div>
                </section>
              )}

            </div>
          )}

        </main>
      </div>
    </div>
  );
}