import { useState, useEffect, useRef } from 'react'; import { useNavigate, useParams } from 'react-router-dom'; import { useLanguage } from '../i18n/LanguageContext'; import { useLocalized } from '../hooks/useLocalized'; import { fonts, radius } from '../styles/theme'; import { haptic } from '../haptic'; import { getTopicTest, startLearningSession, saveLearningAnswer, completeLearningSession, teacherExamples, getLearningAnalytics, startWeakSkillsPractice, getTTS } from '../api'; interface QuestionOption { option_key: string; text_pl: string; text_ru: string; text_uk: string; text_en: string; is_correct: boolean; wrong_because: string | null; } interface TestQuestion { question: { question_id: string; prompt_pl: string; prompt_ru: string; prompt_uk: string; prompt_en: string; question_type: string; skill_tag: string; difficulty: number; }; options: QuestionOption[]; } const TestViewPage: React.FC = () => { const navigate = useNavigate(); const { topicId } = useParams<{ topicId: string }>(); const { t } = useLanguage(); const getLocalized = useLocalized(); const [questions, setQuestions] = useState([]); const [loading, setLoading] = useState(true); const [currentIndex, setCurrentIndex] = useState(0); const [selectedAnswers, setSelectedAnswers] = useState>({}); const [textInputValue, setTextInputValue] = useState(''); const [sessionId, setSessionId] = useState(null); const [isCompleting, setIsCompleting] = useState(false); const [testResult, setTestResult] = useState<{ total: number; correct_count: number } | null>(null); const startTimeRef = useRef(Date.now()); // 🔧 НОВОЕ: состояния для примеров и практики const [showExamplesModal, setShowExamplesModal] = useState(false); const [examplesText, setExamplesText] = useState(''); const [isLoadingExamples, setIsLoadingExamples] = useState(false); const [examplesError, setExamplesError] = useState(null); const [isPlayingExamples, setIsPlayingExamples] = useState(false); const [isStartingPractice, setIsStartingPractice] = useState(false); // 🔧 ФИКС (24.09.2026): ALERT_IN_TELEGRAM_MINIAPP — toast вместо alert(). const [toastMessage, setToastMessage] = useState(null); // 🔧 ФИКС (24.09.2026): TESTVIEW_TOAST_NO_CLEANUP — // храним таймер для очистки. const toastTimeoutRef = useRef | null>(null); const audioRef = useRef(null); // 🔧 ФИКС (24.09.2026): URL_LEAK_TESTVIEW — храним URL для revoke. const audioUrlRef = useRef(null); const brandColor = '#A970D6'; const textColor = '#1A1A2E'; const subColor = '#6B7280'; const bgColor = '#F4F5F7'; const cardBg = 'rgba(255,255,255,0.55)'; const glass = (extra: React.CSSProperties = {}): React.CSSProperties => ({ background: cardBg, backdropFilter: 'blur(24px) saturate(180%)', WebkitBackdropFilter: 'blur(24px) saturate(180%)', border: '1px solid rgba(255,255,255,0.7)', boxShadow: '0 8px 32px rgba(31,38,73,0.10), inset 0 1px 0 rgba(255,255,255,0.85)', ...extra, }); // 🔧 ФИКС (24.09.2026): ALERT_IN_TELEGRAM_MINIAPP — helper для toast. // 🔧 ФИКС (24.09.2026): TESTVIEW_TOAST_NO_CLEANUP — сохраняем таймер. const showToast = (msg: string) => { setToastMessage(msg); if (toastTimeoutRef.current) clearTimeout(toastTimeoutRef.current); toastTimeoutRef.current = setTimeout(() => setToastMessage(null), 2500); }; useEffect(() => { if (topicId) { setLoading(true); getTopicTest(topicId) .then((data: any) => { if (data.test && data.test.length > 0) { setQuestions(data.test); return startLearningSession('A1', topicId, 'topic_test'); } else { throw new Error('No test questions'); } }) .then((sessionData: any) => { setSessionId(sessionData.session_id); }) .catch((e) => { console.error('Error loading test:', e); navigate(`/lessons/topic/${topicId}`); }) .finally(() => setLoading(false)); } }, [topicId]); // 🔧 ФИКС (24.09.2026): URL_LEAK_TESTVIEW — cleanup при unmount. useEffect(() => { return () => { if (audioRef.current) { audioRef.current.pause(); audioRef.current = null; } if (audioUrlRef.current) { try { URL.revokeObjectURL(audioUrlRef.current); } catch { /* ignore */ } audioUrlRef.current = null; } // 🔧 ФИКС (24.09.2026): TESTVIEW_TOAST_NO_CLEANUP if (toastTimeoutRef.current) { clearTimeout(toastTimeoutRef.current); toastTimeoutRef.current = null; } if ('speechSynthesis' in window) { window.speechSynthesis.cancel(); } }; }, []); // 🔧 ФИКС (23.09.2026): TESTVIEW_SAVEANSWER_MISSING_PARAMS — сигнатура // приведена к общему виду (isFinalAnswer, usedHint) — как в LessonViewPage // и PracticeViewPage. Раньше тест не передавал usedHint, и статистика // по подсказкам в тесте не собиралась. const saveAnswer = async ( questionId: string, answer: string, isFinalAnswer: boolean = true, usedHint: boolean = false, ) => { const timeTaken = Date.now() - startTimeRef.current; startTimeRef.current = Date.now(); if (sessionId) { try { await saveLearningAnswer(sessionId, questionId, answer, timeTaken, isFinalAnswer, usedHint); } catch (e) { console.error('Error saving answer:', e); } } }; const handleAnswerSelect = async (questionId: string, optionKey: string) => { // 🔧 ФИКС (01.10.2026): haptic_test_view — выбор варианта haptic.selection(); setSelectedAnswers(prev => ({ ...prev, [questionId]: optionKey })); // 🔧 ФИКС (23.09.2026): обычный ответ — isFinalAnswer=true, usedHint=false await saveAnswer(questionId, optionKey, true, false); }; const handleTextInputChange = async (questionId: string, value: string) => { setTextInputValue(value); setSelectedAnswers(prev => ({ ...prev, [questionId]: value })); }; const handleTextInputBlur = async (questionId: string) => { if (textInputValue.trim()) { // 🔧 ФИКС (23.09.2026): обычный ответ — isFinalAnswer=true, usedHint=false await saveAnswer(questionId, textInputValue.trim(), true, false); } }; const handleNext = async () => { if (currentIndex < questions.length - 1) { setCurrentIndex(prev => prev + 1); setTextInputValue(''); startTimeRef.current = Date.now(); } else { // 🔧 ФИКС (01.10.2026): haptic_test_view — завершение теста haptic.heavy(); setIsCompleting(true); // 🔧 ФИКС (24.09.2026): TESTVIEW_DUPLICATE_SAVE — // ответ последнего вопроса уже сохранён в handleAnswerSelect / // handleTextInputBlur. Повторно НЕ сохраняем — убираем дубль. // (как в PracticeViewPage) // Небольшая задержка для сохранения await new Promise(resolve => setTimeout(resolve, 300)); if (sessionId) { try { const result = await completeLearningSession(sessionId); setTestResult(result); } catch (e) { console.error('Error completing test:', e); } } } }; const handleBack = () => { // 🔧 ФИКС (01.10.2026): haptic_test_view — вибрация возврата haptic.light(); if (currentIndex > 0) { setCurrentIndex(prev => prev - 1); setTextInputValue(''); startTimeRef.current = Date.now(); } }; // 🔧 НОВОЕ: загрузка примеров по теме const handleLoadExamples = async () => { if (isLoadingExamples) return; setIsLoadingExamples(true); setExamplesError(null); setExamplesText(''); setShowExamplesModal(true); try { const data = await teacherExamples('', '', topicId || ''); if (data.limit_exceeded && data.message) { setExamplesError(data.message); } else if (data.response) { setExamplesText(data.response); } else { setExamplesError(t('testNoExamples')); } } catch (e) { console.error('Error loading examples:', e); setExamplesError(t('teacherAIError')); } finally { setIsLoadingExamples(false); } }; // 🔧 НОВОЕ: озвучка примеров (первый польский пример) const handlePlayExamples = async () => { if (!examplesText || isPlayingExamples) return; // Извлекаем первый польский пример const lines = examplesText.split('\n'); let polishText = ''; for (const line of lines) { if (line.includes('🇵🇱')) { polishText = line.split('🇵🇱')[1]?.split('→')[0]?.trim() || ''; break; } } if (!polishText) return; if (audioRef.current) { audioRef.current.pause(); audioRef.current = null; } // 🔧 ФИКС (24.09.2026): URL_LEAK_TESTVIEW — освобождаем предыдущий URL if (audioUrlRef.current) { try { URL.revokeObjectURL(audioUrlRef.current); } catch { /* ignore */ } audioUrlRef.current = null; } if ('speechSynthesis' in window) { window.speechSynthesis.cancel(); } setIsPlayingExamples(true); try { const audioBlob = await getTTS(polishText, 'male'); const audioUrl = URL.createObjectURL(audioBlob); audioUrlRef.current = audioUrl; // 🔧 сохраняем для revoke const audio = new Audio(audioUrl); audioRef.current = audio; audio.onended = () => { setIsPlayingExamples(false); // 🔧 ФИКС (24.09.2026): освобождаем URL if (audioUrlRef.current === audioUrl) { try { URL.revokeObjectURL(audioUrl); } catch { /* ignore */ } audioUrlRef.current = null; } }; audio.onerror = () => { setIsPlayingExamples(false); if (audioUrlRef.current === audioUrl) { try { URL.revokeObjectURL(audioUrl); } catch { /* ignore */ } audioUrlRef.current = null; } }; await audio.play(); } catch (e) { console.error('TTS error:', e); setIsPlayingExamples(false); } }; // 🔧 НОВОЕ: практика слабых тем const handleStartPractice = async () => { if (isStartingPractice) return; setIsStartingPractice(true); try { // Проверяем, есть ли слабые темы const analytics = await getLearningAnalytics(); if (!analytics.has_practice_available) { // 🔧 ФИКС (24.09.2026): ALERT_IN_TELEGRAM_MINIAPP — toast вместо alert() showToast(t('testPracticeNoWeak')); setIsStartingPractice(false); return; } const data = await startWeakSkillsPractice(); if (data.has_weak_skills && data.session_id) { navigate('/lessons/practice', { state: { sessionId: data.session_id, questions: data.questions, explanations: data.explanations, }, }); } else { // 🔧 ФИКС (24.09.2026): toast вместо alert() showToast(data.message || t('testPracticeNoWeak')); setIsStartingPractice(false); } } catch (e) { console.error('Error starting practice:', e); // 🔧 ФИКС (24.09.2026): toast вместо alert() showToast(t('teacherAIError')); setIsStartingPractice(false); } }; if (loading) { return (
{t('loading')}
); } // Экран результатов if (testResult) { const total = testResult.total || 0; const correct = testResult.correct_count || 0; const percentage = total > 0 ? Math.round((correct / total) * 100) : 0; return (
{/* 🔧 ФИКС (24.09.2026): ALERT_IN_TELEGRAM_MINIAPP — toast вместо alert() */} {toastMessage && (
{toastMessage}
)}
{percentage >= 70 ? '🎉' : percentage >= 50 ? '👍' : '💪'}

{t('teacherCompleted')}

= 70 ? '#2ECC71' : percentage >= 50 ? '#F39C12' : '#E74C3C' }}> {percentage}%
{correct} / {total}
{t('testCorrectAnswers')}
{/* 🔧 НОВОЕ: Кнопки "Дай примеры" и "Потренировать слабые темы" */}
{/* 🔧 НОВОЕ: Модалка с примерами */} {showExamplesModal && (
{ if (e.target === e.currentTarget) setShowExamplesModal(false); }} >

💡 {t('testExamplesTitle')}

{isLoadingExamples ? (
{t('loading')}
) : examplesError ? (
⚠️ {examplesError}
) : ( <>
{examplesText}
)}
)}
); } if (questions.length === 0) return null; const currentQuestion = questions[currentIndex]; const isLastQuestion = currentIndex === questions.length - 1; const isProduction = currentQuestion?.question.question_type === 'production'; const isCurrentAnswered = currentQuestion ? !!selectedAnswers[currentQuestion.question.question_id] : false; return (
{/* Заголовок */}

🎓 {t('testTitle')}

{/* Счётчик */}
{t('testQuestion')} {currentIndex + 1} / {questions.length}
{/* Прогресс-бар */}
{/* Вопрос */} {currentQuestion && (

{getLocalized(currentQuestion.question, 'prompt')}

{isProduction ? (
handleTextInputChange(currentQuestion.question.question_id, e.target.value)} onBlur={() => handleTextInputBlur(currentQuestion.question.question_id)} placeholder={t('teacherPlaceholder')} style={{ width: '100%', padding: '16px', borderRadius: radius.lg, border: textInputValue.trim() ? `2px solid ${brandColor}` : '1px solid rgba(255,255,255,0.7)', background: textInputValue.trim() ? `${brandColor}10` : cardBg, color: textColor, fontSize: '18px', fontWeight: 600, fontFamily: fonts.main, outline: 'none', textAlign: 'center', transition: 'all 0.2s ease', boxShadow: textInputValue.trim() ? `0 0 15px ${brandColor}30` : '0 2px 8px rgba(31,38,73,0.06)', }} onFocus={(e) => { e.currentTarget.style.borderColor = brandColor; e.currentTarget.style.boxShadow = `0 0 15px ${brandColor}30`; }} />
) : (
{currentQuestion.options.map((option) => { const isSelected = selectedAnswers[currentQuestion.question.question_id] === option.option_key; return ( ); })}
)}
)} {/* Кнопки навигации */}
); }; export default TestViewPage;