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 { getLearningLesson, startLearningSession, saveLearningAnswer, completeLearningSession } 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 Question { 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[]; } interface Example { text_pl: string; text_ru: string; text_uk: string; text_en: string; } interface LessonData { lesson: { lesson_id: string; title_pl: string; title_ru: string; title_uk: string; title_en: string; explanation_pl: string; explanation_ru: string; explanation_uk: string; explanation_en: string; }; examples: Example[]; questions: Question[]; } const LessonViewPage: React.FC = () => { const navigate = useNavigate(); const { lessonId, topicId } = useParams<{ lessonId: string; topicId: string }>(); const { t } = useLanguage(); const getLocalized = useLocalized(); const [lesson, setLesson] = useState(null); const [loading, setLoading] = useState(true); const [currentQuestionIndex, setCurrentQuestionIndex] = useState(0); const [selectedAnswers, setSelectedAnswers] = useState>({}); const [textInputValue, setTextInputValue] = useState(''); const [sessionId, setSessionId] = useState(null); const [isCompleting, setIsCompleting] = useState(false); const [hintUsed, setHintUsed] = useState>({}); const [showHint, setShowHint] = useState(false); const startTimeRef = useRef(Date.now()); // 🔧 ФИКС (25.09.2026): LESSON_NEXT_NO_RESULTS — // экран результатов после последнего вопроса. const [showResults, setShowResults] = useState(false); const [sessionStats, setSessionStats] = useState<{ total: number; correct: number } | null>(null); 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(() => { if (lessonId && topicId) { setLoading(true); getLearningLesson(lessonId) .then((data: any) => { setLesson(data); return startLearningSession('A1', topicId, 'lesson'); }) .then((sessionData: any) => { setSessionId(sessionData.session_id); }) .catch(() => {}) .finally(() => setLoading(false)); } }, [lessonId, topicId]); // 🔧 ИСПРАВЛЕНО: saveAnswer теперь принимает isFinalAnswer и hintUsed 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) => { 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); } }; // 🔧 ФИКС (22.09.2026): подсказка больше НЕ засчитывается как ответ. // Было: saveAnswer(..., correctAnswer, true, true) + setSelectedAnswers(correctAnswer) // → ученик жал «💡 Hint», и вопрос засчитывался как правильный без решения. // Стало: подсказка — только UI. Отправляем факт подсказки с isFinalAnswer=false, // пустым ответом. Вариант в UI НЕ выбирается автоматически. // Кнопка «Далее» ждёт, пока ученик сам выберет ответ. 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 (currentQuestionIndex < (lesson?.questions.length || 0) - 1) { setCurrentQuestionIndex(prev => prev + 1); setTextInputValue(''); startTimeRef.current = Date.now(); } else { setIsCompleting(true); // 🔧 ФИКС (25.09.2026): LESSON_NEXT_NO_RESULTS — // считаем результаты ДО навигации и показываем экран. const questions = lesson?.questions || []; let correct = 0; for (const q of questions) { const selected = selectedAnswers[q.question.question_id]; const correctOpt = q.options.find(o => o.is_correct); if (selected && correctOpt && selected === correctOpt.option_key) { correct++; } } setSessionStats({ total: questions.length, correct }); let completionData: any = null; if (sessionId) { try { completionData = await completeLearningSession(sessionId); } catch (e) { console.error('Error completing session:', e); } } // Если сервер вернул свои цифры — используем их if (completionData?.total !== undefined) { setSessionStats({ total: completionData.total, correct: completionData.correct_count ?? completionData.correct ?? correct, }); } setShowResults(true); setIsCompleting(false); } }; const handleBack = () => { setShowHint(false); if (currentQuestionIndex > 0) { setCurrentQuestionIndex(prev => prev - 1); setTextInputValue(''); startTimeRef.current = Date.now(); } }; // 🔧 ФИКС (25.09.2026): LESSON_NEXT_NO_RESULTS — экран результатов. if (showResults && sessionStats) { const percent = sessionStats.total > 0 ? Math.round((sessionStats.correct / sessionStats.total) * 100) : 0; const isGood = percent >= 70; return (
{isGood ? '🎉' : '💪'}

{t('teacherCompleted') || 'Lekcja ukończona!'}

{sessionStats.correct}
{t('testCorrectAnswers') || 'poprawnych'}
{sessionStats.total}
{t('testQuestion') || 'pytań'}
{percent}%
%
); } if (loading) { return (
{t('loading')}
); } if (!lesson) return null; const currentQuestion = lesson.questions[currentQuestionIndex]; const isLastQuestion = currentQuestionIndex === lesson.questions.length - 1; const isProduction = currentQuestion?.question.question_type === 'production'; const isCurrentAnswered = currentQuestion ? !!selectedAnswers[currentQuestion.question.question_id] : false; // 🔧 ФИКС (23.09.2026): LESSON_HARDCODED_SKILL_TAG — используем optionsLanguage // из данных вопроса (как в TeacherChatPage), а не хардкод skill_tag. // Для любого навыка с optionsLanguage='user' варианты локализуются. const optionsLanguage = (currentQuestion?.question as any)?.options_language; // Fallback: если поле отсутствует — оставляем старое поведение const isTranslationQuestion = optionsLanguage === 'user' || (optionsLanguage === undefined && currentQuestion?.question.skill_tag === 'how_are_you'); const isHintUsed = currentQuestion ? !!hintUsed[currentQuestion.question.question_id] : false; const correctOption = currentQuestion?.options.find(o => o.is_correct); return (
{/* Модалка подсказки */} {showHint && correctOption && (
{ if (e.target === e.currentTarget) setShowHint(false); }} >

💡 {t('hintButton')}

{t('correctOption')}:
{/* 🔧 ФИКС (25.09.2026): LESSON_HINT_SHOWS_POLISH_ONLY (#20) — раньше в подсказке всегда показывался correctOption.text_pl, даже для RU/EN/UK-пользователей. Теперь для вопросов с optionsLanguage='user' показываем локализованный вариант через getLocalized — как и в кнопках вариантов ниже. */}
{isTranslationQuestion ? getLocalized(correctOption, 'text') : correctOption.text_pl}
{correctOption.wrong_because && (
{t('whyLabel')}:
{correctOption.wrong_because}
)}
)} {/* Заголовок */}

{getLocalized(lesson.lesson, 'title')}

{/* Счётчик */}
{t('testQuestion')} {currentQuestionIndex + 1} / {lesson.questions.length}
{/* Объяснение (только на первом вопросе) */} {currentQuestionIndex === 0 && (

{getLocalized(lesson.lesson, 'explanation')}

{lesson.examples.length > 0 && (
{lesson.examples.map((example, i) => (
🇵🇱 {example.text_pl}
{getLocalized(example, 'text')}
))}
)}
)} {/* Вопрос */} {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 LessonViewPage;