import { useState, useEffect, useRef } from 'react'; import { useNavigate, useLocation } 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 { saveLearningAnswer, completeLearningSession } from '../api'; interface PracticeQuestion { 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: Array<{ option_key: string; text_pl: string; text_ru: string; text_uk: string; text_en: string; is_correct: boolean; wrong_because: string | null; }>; } interface PracticeExplanation { skill_tag: string; name: string; explanation_pl?: string; explanation_ru?: string; explanation_uk?: string; explanation_en?: string; } const PracticeViewPage: React.FC = () => { const navigate = useNavigate(); const location = useLocation(); const { t } = useLanguage(); const getLocalized = useLocalized(); const [questions, setQuestions] = useState([]); const [explanations, setExplanations] = useState([]); const [sessionId, setSessionId] = useState(null); const [loading, setLoading] = useState(true); const [currentIndex, setCurrentIndex] = useState(0); const [selectedAnswers, setSelectedAnswers] = useState>({}); const [textInputValue, setTextInputValue] = useState(''); const [isCompleting, setIsCompleting] = useState(false); const [hintUsed, setHintUsed] = useState>({}); const [showHint, setShowHint] = useState(false); const [practiceResult, setPracticeResult] = useState<{ total: number; correct_count: number } | null>(null); const startTimeRef = useRef(Date.now()); const brandColor = '#2ECC71'; 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, }); useEffect(() => { const state = location.state as any; if (state && state.sessionId && state.questions) { setSessionId(state.sessionId); setQuestions(state.questions); setExplanations(state.explanations || []); setLoading(false); } else { navigate('/menu'); } }, [location.state, navigate]); // 🔧 ИСПРАВЛЕНО: saveAnswer теперь принимает isFinalAnswer и 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_practice_view — выбор варианта haptic.selection(); setSelectedAnswers(prev => ({ ...prev, [questionId]: optionKey })); // 🔧 ИСПРАВЛЕНО: обычный ответ — isFinalAnswer=true, hintUsed=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()) { // 🔧 ИСПРАВЛЕНО: обычный ответ — isFinalAnswer=true, hintUsed=false await saveAnswer(questionId, textInputValue.trim(), true, false); } }; // 🔧 ФИКС (23.09.2026): HINT_AUTO_SELECTS_CORRECT — подсказка больше НЕ засчитывается как ответ. // Было: saveAnswer(..., correctAnswer, true, true) + setSelectedAnswers(correctAnswer) // → ученик жал «💡 Подсказка», и вопрос засчитывался как правильный без решения. // Стало: подсказка — только UI. Отправляем факт подсказки с isFinalAnswer=false, // пустым ответом. Вариант в UI НЕ выбирается автоматически. // Кнопка «Далее» ждёт, пока ученик сам выберет ответ. // Паттерн скопирован из LessonViewPage.handleHintClick. const handleHintClick = async () => { if (!currentQuestion || hintUsed[currentQuestion.question.question_id]) return; setHintUsed(prev => ({ ...prev, [currentQuestion.question.question_id]: true })); setShowHint(true); // 🔧 Логируем факт подсказки — но НЕ как финальный ответ. // Пустой answer, isFinalAnswer=false, usedHint=true. await saveAnswer(currentQuestion.question.question_id, '', false, true); }; const handleNext = async () => { setShowHint(false); if (currentIndex < questions.length - 1) { setCurrentIndex(prev => prev + 1); setTextInputValue(''); startTimeRef.current = Date.now(); } else { // 🔧 ФИКС (01.10.2026): haptic_practice_view — завершение практики haptic.heavy(); setIsCompleting(true); // 🔧 ФИКС (24.09.2026): PRACTICE_DUPLICATE_SAVE — // раньше saveLearningAnswer вызывался повторно для последнего вопроса, // хотя он уже был сохранён в handleAnswerSelect / handleTextInputBlur. // Теперь НЕ дублируем — просто завершаем сессию. // Ответ уже сохранён при выборе/вводе. await new Promise(resolve => setTimeout(resolve, 300)); if (sessionId) { try { const result = await completeLearningSession(sessionId); setPracticeResult(result); } catch (e) { console.error('Error completing practice:', e); } } } }; const handleBack = () => { // 🔧 ФИКС (01.10.2026): haptic_practice_view — вибрация возврата haptic.light(); setShowHint(false); if (currentIndex > 0) { setCurrentIndex(prev => prev - 1); setTextInputValue(''); startTimeRef.current = Date.now(); } }; if (loading) { return (
{t('loading')}
); } // Экран результатов if (practiceResult) { const total = practiceResult.total || 0; const correct = practiceResult.correct_count || 0; const percentage = total > 0 ? Math.round((correct / total) * 100) : 0; return (
{percentage >= 70 ? '🎉' : percentage >= 50 ? '👍' : '💪'}

{t('practiceCompleted')}

= 70 ? '#2ECC71' : percentage >= 50 ? '#F39C12' : '#E74C3C' }}> {percentage}%
{correct} / {total}
{t('practiceCorrectAnswers')}
); } 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; const isHintUsed = currentQuestion ? !!hintUsed[currentQuestion.question.question_id] : false; const correctOption = currentQuestion?.options.find(o => o.is_correct); const currentSkillTag = currentQuestion?.question.skill_tag; const currentExplanation = explanations.find(e => e.skill_tag === currentSkillTag); return (
{/* Модалка подсказки */} {showHint && correctOption && (
{ if (e.target === e.currentTarget) setShowHint(false); }} >

💡 {t('hintButton')}

{t('correctOption')}:
{/* 🔧 ФИКС (25.09.2026): PRACTICE_HINT_SHOWS_POLISH_ONLY (#21) — раньше в подсказке всегда показывался correctOption.text_pl, даже для RU/EN/UK-пользователей. В PracticeViewPage все варианты уже локализованы через getLocalized, поэтому просто меняем .text_pl → getLocalized(correctOption, 'text'), чтобы подсказка совпадала с тем, что юзер видел в кнопках. */}
{getLocalized(correctOption, 'text')}
{correctOption.wrong_because && (
{t('whyLabel')}:
{correctOption.wrong_because}
)}
)} {/* Заголовок */}

💪 {t('practiceTitle')}

{/* Счётчик */}
{t('testQuestion')} {currentIndex + 1} / {questions.length}
{/* Прогресс-бар */}
{/* Объяснение навыка (если есть) */} {currentExplanation && (
📖 {currentExplanation.name}
{currentExplanation.explanation_ru && (
{getLocalized(currentExplanation, 'explanation')}
)}
)} {/* Вопрос */} {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 PracticeViewPage;