import { useState, useEffect, useRef } from 'react'; import { useNavigate } from 'react-router-dom'; import { useLanguage } from '../i18n/LanguageContext'; import { useLocalized } from '../hooks/useLocalized'; import { fonts, radius } from '../styles/theme'; import { teacherStart, teacherResume, teacherAnswer, teacherExamples, getLearningAnalytics, startWeakSkillsPractice, getTTS, saveTeacherHistory, clearTeacherHistory, } from '../api'; import TeacherMenuModal from '../components/TeacherMenuModal'; import TypingModal from '../components/TypingModal'; import PronunciationModal from '../components/PronunciationModal'; interface TeacherMessage { id: number; type: 'bot' | 'user' | 'system'; text: string; isQuestion?: boolean; questionType?: 'recognition' | 'production'; questionId?: string; options?: Array<{ option_key: string; text_pl: string; text_ru: string; text_uk: string; text_en: string; is_correct: boolean; }>; optionsLanguage?: 'pl' | 'user'; sessionId?: number; lessonId?: string; topicId?: string; topicName?: string; questionIndex?: number; totalQuestions?: number; commands?: string[]; isCorrect?: boolean; isCompleted?: boolean; hasPolishText?: boolean; isLessonCard?: boolean; } // Экран: что показываем сейчас type ScreenState = | { kind: 'start' } | { kind: 'lesson' } | { kind: 'after-answer' } | { kind: 'completed'; correct: number; total: number }; const STORAGE_KEY = 'filwords_teacher_chat_v2'; const TeacherChatPage: React.FC = () => { const navigate = useNavigate(); const { t } = useLanguage(); const getLocalized = useLocalized(); // ============ СОСТОЯНИЕ ============ const [messages, setMessages] = useState([]); const [screen, setScreen] = useState({ kind: 'start' }); const [inputValue, setInputValue] = useState(''); const [isLoading, setIsLoading] = useState(false); const [sessionId, setSessionId] = useState(null); const [currentLessonId, setCurrentLessonId] = useState(''); const [currentTopicId, setCurrentTopicId] = useState(''); const [currentTopicName, setCurrentTopicName] = useState(''); const [currentLevel, setCurrentLevel] = useState('A1'); const [currentQuestionId, setCurrentQuestionId] = useState(''); const [isPlaying, setIsPlaying] = useState(null); const [showMenuModal, setShowMenuModal] = useState(false); const [showTyping, setShowTyping] = useState(false); const [showPronunciation, setShowPronunciation] = useState(false); const [showExamplesModal, setShowExamplesModal] = useState(false); const [examplesText, setExamplesText] = useState(''); const [isLoadingExamples, setIsLoadingExamples] = useState(false); const [examplesError, setExamplesError] = useState(null); const [isStartingPractice, setIsStartingPractice] = useState(false); const [playingExampleLine, setPlayingExampleLine] = useState(null); const [toastMessage, setToastMessage] = useState(null); // ============ REFS ============ const inputRef = useRef(null); const audioRef = useRef(null); const audioUrlRef = useRef(null); const idRef = useRef(0); const toastTimeoutRef = useRef | null>(null); const historySaveTimeoutRef = useRef | null>(null); const startTimeRef = useRef(Date.now()); const contentRef = useRef(null); // ============ ЦВЕТА ============ const brandColor = '#2ECC71'; const teacherColor = '#8B5CF6'; const lectureColor = '#4FA9E8'; 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, }); // ============ HELPERS ============ const showToast = (msg: string) => { setToastMessage(msg); if (toastTimeoutRef.current) clearTimeout(toastTimeoutRef.current); toastTimeoutRef.current = setTimeout(() => setToastMessage(null), 2500); }; const hasPolishContent = (text: string): boolean => { return text.includes('🇵🇱') || text.includes('→') || /[ąćęłńóśźżĄĆĘŁŃÓŚŹŻ]/.test(text); }; const extractPolishText = (text: string): string => { const lines = text.split('\n'); for (const line of lines) { if (!line.trim()) continue; if (line.includes('🇵🇱')) { const polish = line.split('🇵🇱')[1]?.split('→')[0]?.trim(); if (polish) return polish; } if (line.includes('→')) { const polish = line.split('→')[0]?.trim(); if (polish) return polish; } } return ''; }; // ============ АУДИО ============ const stopAudio = () => { if (audioRef.current) { audioRef.current.pause(); audioRef.current = null; } if (audioUrlRef.current) { try { URL.revokeObjectURL(audioUrlRef.current); } catch { /* ignore */ } audioUrlRef.current = null; } if ('speechSynthesis' in window) { window.speechSynthesis.cancel(); } }; const playText = async (text: string, msgId: number) => { const polishText = extractPolishText(text); if (!polishText) return; stopAudio(); setIsPlaying(msgId); try { const audioBlob = await getTTS(polishText, 'male'); const audioUrl = URL.createObjectURL(audioBlob); audioUrlRef.current = audioUrl; const audio = new Audio(audioUrl); audioRef.current = audio; audio.onended = () => { setIsPlaying(null); if (audioUrlRef.current === audioUrl) { try { URL.revokeObjectURL(audioUrl); } catch { /* ignore */ } audioUrlRef.current = null; } }; audio.onerror = () => { setIsPlaying(null); if (audioUrlRef.current === audioUrl) { try { URL.revokeObjectURL(audioUrl); } catch { /* ignore */ } audioUrlRef.current = null; } }; await audio.play(); } catch (e) { console.error('TTS error:', e); setIsPlaying(null); } }; const playExampleLine = async (line: string, index: number) => { let polishText = ''; if (line.includes('🇵🇱')) { polishText = line.split('🇵🇱')[1]?.split('→')[0]?.trim() || ''; } else if (line.includes('→')) { polishText = line.split('→')[0]?.trim() || ''; } if (!polishText) return; stopAudio(); setPlayingExampleLine(index); try { const audioBlob = await getTTS(polishText, 'male'); const audioUrl = URL.createObjectURL(audioBlob); audioUrlRef.current = audioUrl; const audio = new Audio(audioUrl); audioRef.current = audio; audio.onended = () => { setPlayingExampleLine(null); if (audioUrlRef.current === audioUrl) { try { URL.revokeObjectURL(audioUrl); } catch { /* ignore */ } audioUrlRef.current = null; } }; audio.onerror = () => { setPlayingExampleLine(null); if (audioUrlRef.current === audioUrl) { try { URL.revokeObjectURL(audioUrl); } catch { /* ignore */ } audioUrlRef.current = null; } }; await audio.play(); } catch (e) { console.error('TTS error:', e); setPlayingExampleLine(null); } }; // ============ ВОССТАНОВЛЕНИЕ ============ useEffect(() => { // 1. Загружаем историю из localStorage try { const saved = localStorage.getItem(STORAGE_KEY); if (saved) { const parsed = JSON.parse(saved); if (Array.isArray(parsed) && parsed.length > 0) { setMessages(parsed); const maxId = Math.max(...parsed.map((m: TeacherMessage) => m.id)); idRef.current = maxId + 1; // Восстанавливаем текущий экран const lastQuestion = [...parsed].reverse().find((m: TeacherMessage) => m.isQuestion); const lastMsg = parsed[parsed.length - 1]; if (lastMsg?.isCompleted) { setScreen({ kind: 'completed', correct: 0, total: 0 }); } else if (lastQuestion) { setCurrentQuestionId(lastQuestion.questionId || ''); setSessionId(lastQuestion.sessionId || null); setCurrentLessonId(lastQuestion.lessonId || ''); setCurrentTopicId(lastQuestion.topicId || ''); setCurrentTopicName(lastQuestion.topicName || ''); setScreen({ kind: 'lesson' }); } } } } catch (e) { // ignore } // 2. Запрашиваем resume с сервера teacherResume() .then((resumeData) => { if (resumeData.has_active_session && resumeData.question) { setSessionId(resumeData.session_id || null); setCurrentTopicId(resumeData.topic_id || ''); setCurrentLevel((resumeData as any).level_code || 'A1'); const questionId = resumeData.question.question.question_id; setMessages(prev => { const existingQuestion = [...prev].reverse().find(m => m.isQuestion); if (existingQuestion) { setCurrentQuestionId(existingQuestion.questionId || questionId); setScreen({ kind: 'lesson' }); return prev; } setCurrentQuestionId(questionId); setScreen({ kind: 'lesson' }); const questionMsg: TeacherMessage = { id: idRef.current++, type: 'bot', text: getLocalized(resumeData.question.question, 'prompt'), isQuestion: true, questionType: resumeData.question.question.question_type, questionId: questionId, options: resumeData.question.options, optionsLanguage: resumeData.question.question.options_language || 'pl', sessionId: resumeData.session_id, topicId: resumeData.topic_id, questionIndex: resumeData.question_index, totalQuestions: resumeData.total_questions, }; return [...prev, questionMsg]; }); } }) .catch(() => {}); }, []); // ============ СОХРАНЕНИЕ ============ useEffect(() => { try { localStorage.setItem(STORAGE_KEY, JSON.stringify(messages)); } catch (e) { // ignore } if (messages.length === 0) return; if (historySaveTimeoutRef.current) clearTimeout(historySaveTimeoutRef.current); historySaveTimeoutRef.current = setTimeout(() => { saveTeacherHistory(messages).catch(() => {}); }, 500); return () => { if (historySaveTimeoutRef.current) clearTimeout(historySaveTimeoutRef.current); }; }, [messages]); // ============ ФОКУС ============ useEffect(() => { if (screen.kind === 'lesson') { const lastQuestion = [...messages].reverse().find(m => m.isQuestion); if (lastQuestion?.questionType === 'production') { setTimeout(() => inputRef.current?.focus(), 300); } } }, [screen.kind, messages]); // ============ ФОКУС ============ useEffect(() => { return () => { stopAudio(); if (toastTimeoutRef.current) { clearTimeout(toastTimeoutRef.current); toastTimeoutRef.current = null; } }; }, []); // ============ СКРОЛЛ НАВЕРХ ПРИ СМЕНЕ ЭКРАНА ============ useEffect(() => { if (contentRef.current) { contentRef.current.scrollTop = 0; } }, [screen.kind, currentQuestionId]); // ============ HANDLERS ============ const handleClearChat = () => { setMessages([]); setScreen({ kind: 'start' }); setSessionId(null); setCurrentQuestionId(''); setCurrentLessonId(''); setCurrentTopicId(''); setCurrentTopicName(''); localStorage.removeItem(STORAGE_KEY); clearTeacherHistory().catch(() => {}); idRef.current = 0; setShowMenuModal(false); }; const handleCloseTyping = () => { setShowTyping(false); setShowMenuModal(true); }; const handleClosePronunciation = () => { setShowPronunciation(false); setShowMenuModal(true); }; const handleStart = async () => { if (isLoading) return; setShowMenuModal(false); setIsLoading(true); setSessionId(null); setCurrentQuestionId(''); startTimeRef.current = Date.now(); try { const data = await teacherStart(); if (data.session_id) setSessionId(data.session_id); if (data.lesson_id) setCurrentLessonId(data.lesson_id); if (data.topic_id) setCurrentTopicId(data.topic_id); if (data.topic_name) setCurrentTopicName(data.topic_name); if ((data as any).level_code) setCurrentLevel((data as any).level_code); if (data.question) { // Сохраняем сообщение-объяснение (без вопроса) const lessonCardMsg: TeacherMessage = { id: idRef.current++, type: 'bot', text: data.text, topicId: data.topic_id, topicName: data.topic_name, hasPolishText: hasPolishContent(data.text), isLessonCard: true, }; // Сохраняем сообщение-вопрос const questionMsg: TeacherMessage = { id: idRef.current++, type: 'bot', text: getLocalized(data.question.question, 'prompt'), isQuestion: true, questionType: data.question.question.question_type, questionId: data.question.question.question_id, options: data.question.options, optionsLanguage: data.question.question.options_language || 'pl', sessionId: data.session_id, lessonId: data.lesson_id, topicId: data.topic_id, topicName: data.topic_name, questionIndex: data.question_index, totalQuestions: data.total_questions, }; setMessages(prev => [...prev, lessonCardMsg, questionMsg]); setCurrentQuestionId(data.question.question.question_id); setScreen({ kind: 'lesson' }); } else { // Нет вопроса — урок завершён или тест const botMessage: TeacherMessage = { id: idRef.current++, type: 'bot', text: data.text, topicId: data.topic_id, topicName: data.topic_name, hasPolishText: hasPolishContent(data.text), isCompleted: data.message_type === 'completed', }; setMessages(prev => [...prev, botMessage]); if (data.message_type === 'completed') { setScreen({ kind: 'completed', correct: 0, total: 0 }); } } } catch (e) { console.error('Error starting teacher:', e); showToast(t('teacherAIError') || 'Ошибка'); } finally { setIsLoading(false); } }; const handleAnswer = async (answer: string) => { if (!sessionId || !currentQuestionId || isLoading) return; const timeTaken = Date.now() - startTimeRef.current; startTimeRef.current = Date.now(); setIsLoading(true); try { const data = await teacherAnswer(sessionId, currentQuestionId, answer, timeTaken); let correctAnswerText = data.correct_answer || ''; if (!correctAnswerText) { const currentQuestion = messages.find(m => m.isQuestion && m.questionId === currentQuestionId); if (currentQuestion && currentQuestion.options) { const correctOption = currentQuestion.options.find(o => o.is_correct); if (correctOption) { correctAnswerText = correctOption.text_pl; } } } // Сохраняем reaction-сообщение const reactionMessage: TeacherMessage = { id: idRef.current++, type: 'bot', text: data.reaction, isCorrect: data.is_correct, commands: [ ...(!data.is_correct ? ['/show-answer'] : []), ], hasPolishText: false, }; setMessages(prev => [...prev, reactionMessage]); // Если сессия завершена if (data.session_completed) { const stats = data.session_stats || { total: 0, correct_count: 0 }; const completedMessage: TeacherMessage = { id: idRef.current++, type: 'system', text: t('teacherCompleted') || 'Урок завершён!', isCompleted: true, }; setMessages(prev => [...prev, completedMessage]); setScreen({ kind: 'completed', correct: stats.correct_count, total: stats.total, }); setIsLoading(false); return; } // Если есть следующий вопрос if (data.question) { const nextQuestionMessage: TeacherMessage = { id: idRef.current++, type: 'bot', text: getLocalized(data.question.question, 'prompt'), isQuestion: true, questionType: data.question.question.question_type, questionId: data.question.question.question_id, options: data.question.options, optionsLanguage: data.question.question.options_language || 'pl', questionIndex: data.question_index, totalQuestions: data.question.total_questions, }; setMessages(prev => [...prev, nextQuestionMessage]); setCurrentQuestionId(data.question.question.question_id); } // Показываем экран "after-answer" — с реакцией и кнопкой "Следующий вопрос" setScreen({ kind: 'after-answer' }); } catch (e) { console.error('Error answering:', e); showToast(t('teacherAIError') || 'Ошибка'); } finally { setIsLoading(false); } }; // Переход к следующему вопросу (после ответа) const handleNextQuestion = () => { // Ищем последний вопрос в messages (последний добавленный) const lastQuestion = [...messages].reverse().find(m => m.isQuestion); if (lastQuestion) { setCurrentQuestionId(lastQuestion.questionId || ''); setScreen({ kind: 'lesson' }); } else { // Нет вопроса — урок завершён setScreen({ kind: 'completed', correct: 0, total: 0 }); } }; const handleLoadExamples = async () => { if (isLoadingExamples) return; setIsLoadingExamples(true); setExamplesError(null); setExamplesText(''); setShowExamplesModal(true); try { const data = await teacherExamples('', currentLessonId, currentTopicId); 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 handleStartPractice = async () => { if (isStartingPractice) return; setIsStartingPractice(true); try { const analytics = await getLearningAnalytics(); if (!analytics.has_practice_available) { 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 { showToast(data.message || t('testPracticeNoWeak') || 'Нет слабых навыков'); setIsStartingPractice(false); } } catch (e) { console.error('Error starting practice:', e); showToast(t('teacherAIError') || 'Ошибка'); setIsStartingPractice(false); } }; const handleOptionClick = (option: any) => { handleAnswer(option.option_key); }; const handleSubmitAnswer = () => { const text = inputValue.trim(); if (!text) return; handleAnswer(text); }; const handleKeyDown = (e: React.KeyboardEvent) => { if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); handleSubmitAnswer(); } }; // ============ COMPUTED ============ // Текущий вопрос (последний в messages) const currentQuestion = [...messages].reverse().find(m => m.isQuestion) || null; // Текущее объяснение (последнее isLessonCard) const currentLesson = [...messages].reverse().find(m => m.isLessonCard) || null; // Последняя реакция (если есть) const lastReaction = [...messages].reverse().find(m => m.isCorrect !== undefined && !m.isQuestion) || null; // ============ RENDER ============ return (
{/* Фоновые градиенты */}
{/* Toast */} {toastMessage && (
{toastMessage}
)} {/* Модалка примеров */} {showExamplesModal && (
{ if (e.target === e.currentTarget) setShowExamplesModal(false); }} >

💡 {t('testExamplesTitle') || 'Примеры'}

{isLoadingExamples ? (
{t('loading') || 'Загрузка...'}
) : examplesError ? (
⚠️ {examplesError}
) : ( <>
{examplesText.split('\n').filter(line => line.trim()).map((line, idx) => (
playExampleLine(line, idx)} style={{ padding: '12px 14px', background: playingExampleLine === idx ? 'rgba(79,169,232,0.18)' : 'rgba(79,169,232,0.08)', borderRadius: radius.md, fontSize: '14px', lineHeight: '1.6', color: textColor, cursor: 'pointer', border: playingExampleLine === idx ? '1px solid rgba(79,169,232,0.5)' : '1px solid transparent', display: 'flex', alignItems: 'center', gap: '10px', }} > {line} 🔊
))}
)}
)} {/* Модалки */} setShowMenuModal(false)} onStartLesson={handleStart} onClearChat={handleClearChat} onOpenTyping={() => setShowTyping(true)} onOpenPronunciation={() => setShowPronunciation(true)} /> {/* ============ ОСНОВНОЙ КОНТЕНТ ============ */}
{/* ЗАГОЛОВОК */}
{screen.kind === 'lesson' || screen.kind === 'after-answer' ? (
{currentLevel} {currentQuestion?.questionIndex !== undefined && currentQuestion?.totalQuestions !== undefined && ( {currentQuestion.questionIndex + 1}/{currentQuestion.totalQuestions} )} {currentTopicName || currentLesson?.topicName || t('lessons') || 'Уроки'}
) : (

📚 {t('lessons') || 'Уроки'}

)} {messages.length > 0 && ( )}
{/* КОНТЕНТ */}
{/* ЭКРАН START */} {screen.kind === 'start' && (
🎓

{t('teacherWelcome') || 'Добро пожаловать!'}

)} {/* ЭКРАН LESSON — один урок = одна страница */} {screen.kind === 'lesson' && ( <> {/* Заголовок страницы */}
{currentLevel} · {t('level') || 'Уровень'}
{(currentTopicName || currentLesson?.topicName) && (
{t('topic') || 'Тема'}: {currentTopicName || currentLesson?.topicName}
)}
{currentLesson && (
{currentLesson.text.split('\n')[0]}
)}
{/* Объяснение + примеры (из lessonCard) */} {currentLesson && (
📖 {t('teacherExplanation') || 'Объяснение'}
{currentLesson.text}
{currentLesson.hasPolishText && ( )}
)} {/* Задание (текущий вопрос) */} {currentQuestion && (
✏️ {t('teacherTask') || 'Задание'}
{currentQuestion.questionIndex !== undefined && currentQuestion.totalQuestions !== undefined && ( {currentQuestion.questionIndex + 1} / {currentQuestion.totalQuestions} )}
{currentQuestion.text}
{/* Варианты ответа (recognition) */} {currentQuestion.questionType === 'recognition' && currentQuestion.options && (
{currentQuestion.options.map((option) => ( ))}
)} {/* Ввод (production) */} {currentQuestion.questionType === 'production' && (
setInputValue(e.target.value)} onKeyDown={handleKeyDown} placeholder={t('teacherPlaceholder') || 'Введите ответ'} disabled={isLoading} style={{ flex: 1, padding: '12px 16px', borderRadius: radius.md, border: `1px solid ${teacherColor}30`, background: 'rgba(255,255,255,0.8)', color: textColor, fontSize: '15px', fontFamily: fonts.main, outline: 'none', }} />
)}
)} )} {/* ЭКРАН AFTER-ANSWER — реакция + кнопка "Следующий вопрос" */} {screen.kind === 'after-answer' && (
{/* Реакция */} {lastReaction && (
{lastReaction.isCorrect ? '✅' : '❌'}
{lastReaction.text}
{lastReaction.commands?.includes('/show-answer') && ( )}
)} {/* Кнопка "Следующий вопрос" */}
)} {/* ЭКРАН COMPLETED */} {screen.kind === 'completed' && (
🎉

{t('teacherLessonCompleted') || 'Урок завершён!'}

{screen.total > 0 && (

{screen.correct} / {screen.total} ({Math.round((screen.correct / screen.total) * 100)}%)

)}
)}
); }; export default TeacherChatPage;