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(() => 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(initialUnitId || allUnits[0]?.id || 1); const [searchTerm, setSearchTerm] = useState(""); const [quizAnswers, setQuizAnswers] = useState<{ [qId: number]: number }>({}); const [quizChecked, setQuizChecked] = useState(false); const [quizScore, setQuizScore] = useState(0); const [quizFinished, setQuizFinished] = useState(false); const [showExplanation, setShowExplanation] = useState<{ [qId: number]: boolean }>({}); const [completedUnits, setCompletedUnits] = useState([]); // πŸ“„ PREMIUM PDF READER & PAGINATION STATES const [activeTab, setActiveTab] = useState<'explanation' | 'pdf'>('explanation'); const [pdfPage, setPdfPage] = useState(1); const [pdfZoom, setPdfZoom] = useState(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(() => { 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 (
{/* HEADER */}
πŸ“š

{isKutubxona ? "KUTUBXONA" : "Essential Grammar in Use"} {isKutubxona ? "Real-Time" : "4th Edition"} {!isOnline && ( Offline Kesh )}

{isKutubxona ? "Admin yuklagan maxsus darsliklar va kitoblar" : "Raymond Murphy β€’ Interaktiv Bilingual Nashr"}

O'quvchi: {userName} Kitoblar: {allUnits.length} ta darslik ({userHp} HP)
πŸ“–
{/* CORE BODY GRID */}
{/* LEFT INDEX BAR */} {/* CENTER SPLIT PAGES CONTROLS AND CONTENT VIEW */}
{!isOnline && (

Oflayn Rejim Faol

Ushbu kitob va uning amaliy mashqlari keshdan yuklangan va to'liq oflayn ishlaydi.

Keşlash Faol ⚑
)} {/* TABS SELECTOR IF PDF EXISTS */} {activeUnit?.pdfUrl && (
)} {activeTab === 'pdf' && activeUnit?.pdfUrl ? ( /* BRAND NEW IMMERSIVE INTERACTIVE PDF READER VIEW WITH ADVANCED PAGINATION */
{/* Left Column: Interactive PDF Canvas Viewport with Paginating overlay */}
{/* Header Actions */}
Ilova ichida o'quvchi
{/* Mode Selector & Engine Toggles */}
{/* View Engine Toggle */}
{/* View Mode Toggle: Scroll vs Paginated */}
{/* Zoom actions */}
{pdfZoom}%
{/* Standard PDF Paginator Bar */} {pdfViewMode === 'paginated' && (
{/* Buttons & Number Selector */}
{/* Active Input selector */}
Sahifa { 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" /> / 50-gacha
{/* Smooth Range Slider for rapid page scrub */}
SLAYDER: setPdfPage(parseInt(e.target.value))} className="flex-1 accent-red-650 h-1 bg-slate-950 rounded-lg appearance-none cursor-pointer" />
)} {/* PDF rendering viewport frame wrapper */}
{/* Native scroll page tracking indicator when scroll view is active */} {pdfViewMode === 'scroll' && (
Avto-sahifalash: barcha sahifalar ketma-ket
)} {/* PDF embed viewport */}