Files
filwordspl-frontend/src/pages/TestViewPage.tsx
T
Drobysh cae2443dda feat(haptic): вибрация на 7 страницах — уроки, тест, практика, учитель, лекции, произношение
- LessonsPage: selection() на выбор уровня/темы, кнопка назад
- LessonViewPage: selection() на ответ, heavy() на завершение урока
- TestViewPage: selection() на ответ, heavy() на завершение, medium() на примеры/практику
- PracticeViewPage: selection() на ответ, heavy() на завершение практики
- TeacherChatPage: medium() на старт, success()/error() на ответ учителя
- LecturesPage: selection() на открытие, medium() на скачивание
- PronunciationPage: selection() на тап по слову, light() на следующее

Глобальный useGlobalHaptic в App.tsx вешает light() на все кнопки.
На кнопках с явным haptic — data-no-haptic="true" против двойной вибрации.
2026-10-01 15:54:27 +03:00

844 lines
31 KiB
TypeScript

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<TestQuestion[]>([]);
const [loading, setLoading] = useState(true);
const [currentIndex, setCurrentIndex] = useState(0);
const [selectedAnswers, setSelectedAnswers] = useState<Record<string, string>>({});
const [textInputValue, setTextInputValue] = useState('');
const [sessionId, setSessionId] = useState<number | null>(null);
const [isCompleting, setIsCompleting] = useState(false);
const [testResult, setTestResult] = useState<{ total: number; correct_count: number } | null>(null);
const startTimeRef = useRef<number>(Date.now());
// 🔧 НОВОЕ: состояния для примеров и практики
const [showExamplesModal, setShowExamplesModal] = useState(false);
const [examplesText, setExamplesText] = useState('');
const [isLoadingExamples, setIsLoadingExamples] = useState(false);
const [examplesError, setExamplesError] = useState<string | null>(null);
const [isPlayingExamples, setIsPlayingExamples] = useState(false);
const [isStartingPractice, setIsStartingPractice] = useState(false);
// 🔧 ФИКС (24.09.2026): ALERT_IN_TELEGRAM_MINIAPP — toast вместо alert().
const [toastMessage, setToastMessage] = useState<string | null>(null);
// 🔧 ФИКС (24.09.2026): TESTVIEW_TOAST_NO_CLEANUP —
// храним таймер для очистки.
const toastTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const audioRef = useRef<HTMLAudioElement | null>(null);
// 🔧 ФИКС (24.09.2026): URL_LEAK_TESTVIEW — храним URL для revoke.
const audioUrlRef = useRef<string | null>(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 (
<div style={{
minHeight: '100vh',
background: bgColor,
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
color: subColor,
fontFamily: fonts.main,
fontSize: '18px',
}}>
{t('loading')}
</div>
);
}
// Экран результатов
if (testResult) {
const total = testResult.total || 0;
const correct = testResult.correct_count || 0;
const percentage = total > 0 ? Math.round((correct / total) * 100) : 0;
return (
<div style={{
minHeight: '100vh',
background: bgColor,
color: textColor,
fontFamily: fonts.main,
display: 'flex',
flexDirection: 'column',
alignItems: 'center',
justifyContent: 'center',
padding: '24px',
}}>
{/* 🔧 ФИКС (24.09.2026): ALERT_IN_TELEGRAM_MINIAPP — toast вместо alert() */}
{toastMessage && (
<div style={{
position: 'fixed',
top: '20px',
left: '50%',
transform: 'translateX(-50%)',
zIndex: 999,
padding: '12px 20px',
background: 'rgba(26,26,46,0.95)',
color: '#FFFFFF',
fontSize: '14px',
fontWeight: 600,
borderRadius: radius.md,
boxShadow: '0 8px 24px rgba(0,0,0,0.25)',
maxWidth: '90vw',
textAlign: 'center',
}}>
{toastMessage}
</div>
)}
<div style={{ fontSize: '64px', marginBottom: '16px' }}>
{percentage >= 70 ? '🎉' : percentage >= 50 ? '👍' : '💪'}
</div>
<h1 style={{ fontSize: '24px', fontWeight: 900, margin: '0 0 8px 0', textAlign: 'center' }}>
{t('teacherCompleted')}
</h1>
<div style={{
...glass({
padding: '20px',
borderRadius: radius.lg,
textAlign: 'center',
marginTop: '16px',
width: '100%',
maxWidth: '300px',
}),
}}>
<div style={{ fontSize: '48px', fontWeight: 900, color: percentage >= 70 ? '#2ECC71' : percentage >= 50 ? '#F39C12' : '#E74C3C' }}>
{percentage}%
</div>
<div style={{ fontSize: '18px', color: subColor, marginTop: '8px', fontWeight: 600 }}>
{correct} / {total}
</div>
<div style={{ fontSize: '12px', color: subColor, marginTop: '4px' }}>
{t('testCorrectAnswers')}
</div>
</div>
{/* 🔧 НОВОЕ: Кнопки "Дай примеры" и "Потренировать слабые темы" */}
<div style={{ marginTop: '20px', width: '100%', maxWidth: '300px', display: 'flex', flexDirection: 'column', gap: '10px' }}>
<button
onClick={() => {
// 🔧 ФИКС (01.10.2026): haptic_test_view — вибрация загрузки примеров
haptic.medium();
handleLoadExamples();
}}
data-no-haptic="true"
disabled={isLoadingExamples}
style={{
width: '100%',
padding: '14px 20px',
borderRadius: radius.lg,
border: 'none',
background: isLoadingExamples
? 'rgba(0,0,0,0.1)'
: `linear-gradient(135deg, #4FA9E8, #3B82F6)`,
color: '#FFFFFF',
fontSize: '15px',
fontWeight: 700,
cursor: isLoadingExamples ? 'default' : 'pointer',
boxShadow: isLoadingExamples ? 'none' : '0 4px 15px rgba(79,169,232,0.4)',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
gap: '8px',
}}
onTouchStart={(e) => { if (!isLoadingExamples) e.currentTarget.style.transform = 'scale(0.96)'; }}
onTouchEnd={(e) => { e.currentTarget.style.transform = 'scale(1)'; }}
>
💡 {t('testExamplesButton')}
</button>
<button
onClick={() => {
// 🔧 ФИКС (01.10.2026): haptic_test_view — вибрация старта практики
haptic.medium();
handleStartPractice();
}}
data-no-haptic="true"
disabled={isStartingPractice}
style={{
width: '100%',
padding: '14px 20px',
borderRadius: radius.lg,
border: 'none',
background: isStartingPractice
? 'rgba(0,0,0,0.1)'
: `linear-gradient(135deg, #2ECC71, #27AE60)`,
color: '#FFFFFF',
fontSize: '15px',
fontWeight: 700,
cursor: isStartingPractice ? 'default' : 'pointer',
boxShadow: isStartingPractice ? 'none' : '0 4px 15px rgba(46,204,113,0.4)',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
gap: '8px',
}}
onTouchStart={(e) => { if (!isStartingPractice) e.currentTarget.style.transform = 'scale(0.96)'; }}
onTouchEnd={(e) => { e.currentTarget.style.transform = 'scale(1)'; }}
>
🎯 {t('testPracticeButton')}
</button>
</div>
<button
onClick={() => navigate(`/lessons/topic/${topicId}`)}
style={{
marginTop: '12px',
padding: '16px 32px',
borderRadius: radius.lg,
border: 'none',
background: `linear-gradient(135deg, ${brandColor}, #8B5CF6)`,
color: '#FFFFFF',
fontSize: '16px',
fontWeight: 700,
cursor: 'pointer',
boxShadow: `0 4px 15px ${brandColor}40`,
width: '100%',
maxWidth: '300px',
}}
onTouchStart={(e) => { e.currentTarget.style.transform = 'scale(0.96)'; }}
onTouchEnd={(e) => { e.currentTarget.style.transform = 'scale(1)'; }}
>
{t('testBackToTopic')}
</button>
{/* 🔧 НОВОЕ: Модалка с примерами */}
{showExamplesModal && (
<div
style={{
position: 'fixed', top: 0, left: 0, right: 0, bottom: 0,
background: 'rgba(20,22,35,0.25)', zIndex: 500,
display: 'flex', alignItems: 'center', justifyContent: 'center',
padding: '20px',
backdropFilter: 'blur(4px)', WebkitBackdropFilter: 'blur(4px)',
}}
onClick={(e) => { if (e.target === e.currentTarget) setShowExamplesModal(false); }}
>
<div style={{
...glass({
borderRadius: radius.lg,
padding: '24px',
width: '100%',
maxWidth: '400px',
maxHeight: '80vh',
overflow: 'auto',
boxShadow: '0 24px 60px rgba(31,38,73,0.20), inset 0 1px 0 rgba(255,255,255,0.85)',
}),
}}>
<h3 style={{
margin: '0 0 16px 0',
fontSize: '18px',
fontWeight: 800,
textAlign: 'center',
color: textColor,
}}>
💡 {t('testExamplesTitle')}
</h3>
{isLoadingExamples ? (
<div style={{ textAlign: 'center', padding: '30px', color: subColor, fontSize: '14px' }}>
{t('loading')}
</div>
) : examplesError ? (
<div style={{ textAlign: 'center', padding: '20px', color: '#E74C3C', fontSize: '14px', fontWeight: 600 }}>
⚠️ {examplesError}
</div>
) : (
<>
<div style={{
padding: '16px',
background: 'rgba(79,169,232,0.08)',
borderRadius: radius.md,
fontSize: '14px',
lineHeight: '1.7',
color: textColor,
whiteSpace: 'pre-line',
marginBottom: '16px',
}}>
{examplesText}
</div>
<div style={{ display: 'flex', gap: '10px' }}>
<button
onClick={handlePlayExamples}
disabled={isPlayingExamples}
style={{
padding: '12px 16px',
borderRadius: radius.md,
border: `1px solid ${brandColor}40`,
background: isPlayingExamples ? `${brandColor}30` : 'rgba(255,255,255,0.8)',
color: brandColor,
fontSize: '14px',
fontWeight: 700,
cursor: isPlayingExamples ? 'default' : 'pointer',
flexShrink: 0,
}}
>
🔊
</button>
<button
onClick={() => setShowExamplesModal(false)}
style={{
flex: 1,
padding: '12px',
borderRadius: radius.md,
border: 'none',
background: `linear-gradient(135deg, #4FA9E8, #3B82F6)`,
color: '#FFFFFF',
fontSize: '14px',
fontWeight: 700,
cursor: 'pointer',
}}
>
{t('teacherClose')}
</button>
</div>
</>
)}
</div>
</div>
)}
</div>
);
}
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 (
<div style={{
minHeight: '100vh',
background: bgColor,
color: textColor,
fontFamily: fonts.main,
padding: '24px',
display: 'flex',
flexDirection: 'column',
position: 'relative',
overflow: 'hidden',
}}>
<div style={{ position: 'fixed', top: '-80px', right: '-60px', width: '260px', height: '260px', borderRadius: '50%', background: brandColor, opacity: 0.18, filter: 'blur(90px)', pointerEvents: 'none', zIndex: 0 }} />
<style>{`
@keyframes fadeInUp {
0% { transform: translateY(10px); opacity: 0; }
100% { transform: translateY(0); opacity: 1; }
}
@keyframes optionSelect {
0% { transform: scale(1); }
50% { transform: scale(1.05); }
100% { transform: scale(1); }
}
`}</style>
<div style={{ position: 'relative', zIndex: 1, display: 'flex', flexDirection: 'column', flex: 1 }}>
{/* Заголовок */}
<div style={{
display: 'flex',
alignItems: 'center',
gap: '16px',
marginBottom: '20px',
animation: 'fadeInUp 0.3s ease',
}}>
<button
onClick={() => navigate(`/lessons/topic/${topicId}`)}
style={{
...glass({
padding: '10px 18px',
borderRadius: radius.md,
}),
color: textColor,
fontSize: '14px',
fontWeight: 600,
cursor: 'pointer',
transition: 'transform 0.2s ease',
}}
onTouchStart={(e) => { e.currentTarget.style.transform = 'scale(0.95)'; }}
onTouchEnd={(e) => { e.currentTarget.style.transform = 'scale(1)'; }}
>
← {t('back')}
</button>
<h1 style={{ fontSize: '18px', fontWeight: 700, margin: 0, color: textColor, flex: 1, textAlign: 'center' }}>
🎓 {t('testTitle')}
</h1>
</div>
{/* Счётчик */}
<div style={{ textAlign: 'center', marginBottom: '16px', color: subColor, fontSize: '13px' }}>
{t('testQuestion')} {currentIndex + 1} / {questions.length}
</div>
{/* Прогресс-бар */}
<div style={{
width: '100%',
height: '4px',
background: 'rgba(0,0,0,0.06)',
borderRadius: '2px',
marginBottom: '20px',
overflow: 'hidden',
}}>
<div style={{
width: `${((currentIndex + 1) / questions.length) * 100}%`,
height: '100%',
background: `linear-gradient(90deg, ${brandColor}, #8B5CF6)`,
borderRadius: '2px',
transition: 'width 0.3s ease',
}} />
</div>
{/* Вопрос */}
{currentQuestion && (
<div style={{ animation: 'fadeInUp 0.3s ease 0.15s both', flex: 1 }}>
<p style={{ fontSize: '16px', fontWeight: 600, color: textColor, marginBottom: '16px' }}>
{getLocalized(currentQuestion.question, 'prompt')}
</p>
{isProduction ? (
<div>
<input
type="text"
value={textInputValue}
onChange={(e) => 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`;
}}
/>
</div>
) : (
<div style={{ display: 'flex', flexDirection: 'column', gap: '10px' }}>
{currentQuestion.options.map((option) => {
const isSelected = selectedAnswers[currentQuestion.question.question_id] === option.option_key;
return (
<button
key={option.option_key}
data-no-haptic="true"
onClick={() => handleAnswerSelect(currentQuestion.question.question_id, option.option_key)}
style={{
padding: '14px 16px',
borderRadius: radius.md,
border: isSelected ? `2px solid ${brandColor}` : '1px solid rgba(255,255,255,0.7)',
background: isSelected ? `${brandColor}15` : cardBg,
color: textColor,
fontSize: '15px',
fontWeight: isSelected ? 700 : 500,
cursor: 'pointer',
display: 'flex',
alignItems: 'center',
gap: '10px',
boxShadow: isSelected ? `0 0 10px ${brandColor}30` : '0 2px 8px rgba(31,38,73,0.06)',
transition: 'all 0.2s ease',
animation: isSelected ? 'optionSelect 0.3s ease' : 'none',
}}
onTouchStart={(e) => { e.currentTarget.style.transform = 'scale(0.97)'; }}
onTouchEnd={(e) => { e.currentTarget.style.transform = 'scale(1)'; }}
>
<span style={{
width: '20px',
height: '20px',
borderRadius: '50%',
border: isSelected ? `2px solid ${brandColor}` : '2px solid rgba(0,0,0,0.2)',
background: isSelected ? brandColor : 'transparent',
flexShrink: 0,
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
}}>
{isSelected && <span style={{ width: '8px', height: '8px', borderRadius: '50%', background: '#FFFFFF' }} />}
</span>
<span>{option.text_pl}</span>
</button>
);
})}
</div>
)}
</div>
)}
{/* Кнопки навигации */}
<div style={{
display: 'flex',
gap: '12px',
marginTop: '20px',
animation: 'fadeInUp 0.3s ease 0.3s both',
}}>
<button
onClick={handleBack}
disabled={currentIndex === 0 || isCompleting}
style={{
...glass({
padding: '14px 20px',
borderRadius: radius.md,
}),
color: currentIndex === 0 ? subColor : textColor,
fontSize: '14px',
fontWeight: 600,
cursor: currentIndex === 0 ? 'default' : 'pointer',
opacity: currentIndex === 0 ? 0.5 : 1,
transition: 'all 0.2s ease',
}}
>
← {t('back')}
</button>
<button
onClick={handleNext}
data-no-haptic="true"
disabled={!isCurrentAnswered || isCompleting}
style={{
flex: 1,
padding: '14px 20px',
borderRadius: radius.md,
border: 'none',
background: isCurrentAnswered
? `linear-gradient(135deg, ${brandColor}, #8B5CF6)`
: 'rgba(0,0,0,0.1)',
color: '#FFFFFF',
fontSize: '14px',
fontWeight: 700,
cursor: isCurrentAnswered ? 'pointer' : 'default',
transition: 'all 0.2s ease',
boxShadow: isCurrentAnswered ? `0 4px 15px ${brandColor}40` : 'none',
opacity: isCompleting ? 0.7 : 1,
}}
onTouchStart={(e) => {
if (isCurrentAnswered && !isCompleting) {
e.currentTarget.style.transform = 'scale(0.96)';
}
}}
onTouchEnd={(e) => { e.currentTarget.style.transform = 'scale(1)'; }}
>
{isCompleting
? t('testChecking')
: isLastQuestion
? t('testFinish')
: `${t('next')} →`}
</button>
</div>
</div>
</div>
);
};
export default TestViewPage;