initial commit (frontend)

This commit is contained in:
2026-09-20 15:08:32 +03:00
commit 04cc53e66d
84 changed files with 36264 additions and 0 deletions
+816
View File
@@ -0,0 +1,816 @@
import { useState, useEffect, useCallback, useRef } from 'react';
import { useNavigate } from 'react-router-dom';
import { useLanguage } from '../i18n/LanguageContext';
import { fonts, radius } from '../styles/theme';
import { getBubbleLevel, completeBubbleLevel, getBubbleProgress, fetchProgress } from '../api';
import RulesModal from '../components/RulesModal';
import { useAchievements } from '../hooks/useAchievements';
interface BubbleWord {
word_pl: string;
translation: string;
parts: string[];
}
interface Bubble {
text: string;
word_pl: string;
}
const BubbleWordsPage: React.FC = () => {
const navigate = useNavigate();
const { t } = useLanguage();
const [words, setWords] = useState<BubbleWord[]>([]);
const [bubbles, setBubbles] = useState<Bubble[]>([]);
const [loading, setLoading] = useState(true);
const [totalScore, setTotalScore] = useState(0);
const [hintsUsed, setHintsUsed] = useState(0);
const [firstLetterHintsUsed, setFirstLetterHintsUsed] = useState(0);
const [showWordModal, setShowWordModal] = useState(false);
const [selectedBubbles, setSelectedBubbles] = useState<Bubble[]>([]);
const [foundWords, setFoundWords] = useState<string[]>([]);
const [completed, setCompleted] = useState(false);
const [isTransitioning, setIsTransitioning] = useState(false);
const [showRules, setShowRules] = useState(false);
const [message, setMessage] = useState<string | null>(null);
const [errorMessage, setErrorMessage] = useState<string | null>(null);
const [levelsCompleted, setLevelsCompleted] = useState(0);
const [bubbleLevel, setBubbleLevel] = useState(1);
const [currentLevel, setCurrentLevel] = useState('A1');
const [animationsReady, setAnimationsReady] = useState(false);
const [hintHighlightedBubble, setHintHighlightedBubble] = useState<string | null>(null);
const { activeAchievement, showAchievement, resetAchievements } = useAchievements();
const isMountedRef = useRef(true);
const messageTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const hintTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const startTimeRef = useRef<number>(0);
const rulesShownRef = useRef(false);
const maxFirstLetterHints = 3;
const brandColor = '#2ECC71';
const palette = { bubble: '#4FA9E8' };
const textColor = '#1A1A2E';
const subColor = '#6B7280';
const bgColor = '#F4F5F7';
const glass = (extra: React.CSSProperties = {}): React.CSSProperties => ({
background: 'rgba(255,255,255,0.55)',
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(() => {
isMountedRef.current = true;
// Автопоказ правил при первом входе
if (!rulesShownRef.current) {
rulesShownRef.current = true;
const rulesSeen = localStorage.getItem('filwords_rules_bubble');
if (!rulesSeen) {
setTimeout(() => {
if (isMountedRef.current) {
setShowRules(true);
localStorage.setItem('filwords_rules_bubble', '1');
}
}, 500);
}
}
return () => {
isMountedRef.current = false;
if (messageTimeoutRef.current) clearTimeout(messageTimeoutRef.current);
if (hintTimeoutRef.current) clearTimeout(hintTimeoutRef.current);
};
}, []);
const fetchLevel = useCallback(() => {
setLoading(true);
setSelectedBubbles([]);
setFoundWords([]);
setCompleted(false);
setIsTransitioning(false);
setHintsUsed(0);
setFirstLetterHintsUsed(0);
setShowWordModal(false);
setAnimationsReady(false);
setHintHighlightedBubble(null);
resetAchievements();
startTimeRef.current = Date.now();
getBubbleLevel()
.then((data: any) => {
if (isMountedRef.current) {
setWords(data.words || []);
setBubbles(data.bubbles || []);
setBubbleLevel(data.level || 1);
setTimeout(() => {
if (isMountedRef.current) setAnimationsReady(true);
}, 50);
}
})
.catch(() => {
if (isMountedRef.current) navigate('/menu');
})
.finally(() => {
if (isMountedRef.current) setLoading(false);
});
fetchProgress()
.then((data: any) => {
if (isMountedRef.current) {
setTotalScore(data.total_score || 0);
if (data.current_level) {
setCurrentLevel(data.current_level);
}
}
})
.catch(() => {});
getBubbleProgress()
.then((data: any) => {
if (isMountedRef.current) setLevelsCompleted(data.levels_completed || 0);
})
.catch(() => {});
}, [navigate, resetAchievements]);
useEffect(() => {
fetchLevel();
}, [fetchLevel]);
const showMessage = (msg: string) => {
if (!isMountedRef.current) return;
setMessage(msg);
if (messageTimeoutRef.current) clearTimeout(messageTimeoutRef.current);
messageTimeoutRef.current = setTimeout(() => {
if (isMountedRef.current) setMessage(null);
}, 1500);
};
const handleBubbleClick = useCallback((bubble: Bubble) => {
if (completed || isTransitioning) return;
if (foundWords.includes(bubble.word_pl)) return;
setSelectedBubbles(prev => {
const alreadySelected = prev.find(b => b.text === bubble.text && b.word_pl === bubble.word_pl);
if (alreadySelected) {
return prev.filter(b => !(b.text === bubble.text && b.word_pl === bubble.word_pl));
}
return [...prev, bubble];
});
if (window.Telegram?.WebApp?.HapticFeedback) {
window.Telegram.WebApp.HapticFeedback.impactOccurred('light');
}
}, [completed, isTransitioning, foundWords]);
useEffect(() => {
if (selectedBubbles.length === 0) return;
const grouped: Record<string, string> = {};
selectedBubbles.forEach(b => {
if (!grouped[b.word_pl]) grouped[b.word_pl] = '';
grouped[b.word_pl] += b.text;
});
for (const word of words) {
const assembled = grouped[word.word_pl] || '';
if (assembled === word.word_pl && !foundWords.includes(word.word_pl)) {
const newFoundWords = [...foundWords, word.word_pl];
setFoundWords(newFoundWords);
setSelectedBubbles(prev => prev.filter(b => b.word_pl !== word.word_pl));
showMessage(`✅ ${word.word_pl}`);
if (window.Telegram?.WebApp?.HapticFeedback) {
window.Telegram.WebApp.HapticFeedback.impactOccurred('medium');
}
if (newFoundWords.length === words.length && !isTransitioning) {
setIsTransitioning(true);
setCompleted(true);
const completionTime = Math.floor((Date.now() - startTimeRef.current) / 1000);
if (window.Telegram?.WebApp?.HapticFeedback) {
window.Telegram.WebApp.HapticFeedback.impactOccurred('heavy');
}
completeBubbleLevel(hintsUsed, words.length, completionTime)
.then((data: any) => {
if (isMountedRef.current) {
setTotalScore(prev => prev + (data.score || 0));
setLevelsCompleted(prev => prev + 1);
fetchProgress().catch(() => {});
if (data.new_achievements && data.new_achievements.length > 0) {
data.new_achievements.forEach((ach: any) => {
showAchievement({
id: ach.code,
icon: ach.icon,
name: ach.name,
});
});
}
}
})
.catch(() => {});
setTimeout(() => {
if (isMountedRef.current) fetchLevel();
}, 2000);
}
break;
}
}
}, [selectedBubbles, words, foundWords, isTransitioning, hintsUsed, fetchLevel, showAchievement]);
const handleFirstLetterHint = () => {
if (firstLetterHintsUsed >= maxFirstLetterHints) {
setErrorMessage('⚠️ ' + (t('noMoreFirstLetterHints') || 'No more hints'));
return;
}
const notFoundWords = words.filter(w => !foundWords.includes(w.word_pl));
if (notFoundWords.length === 0) return;
const randomWord = notFoundWords[Math.floor(Math.random() * notFoundWords.length)];
const firstPart = randomWord.parts[0];
const hintKey = `${firstPart}-${randomWord.word_pl}`;
setHintHighlightedBubble(hintKey);
if (hintTimeoutRef.current) clearTimeout(hintTimeoutRef.current);
hintTimeoutRef.current = setTimeout(() => {
if (isMountedRef.current) setHintHighlightedBubble(null);
}, 2000);
setFirstLetterHintsUsed(prev => prev + 1);
setHintsUsed(prev => prev + 1);
setErrorMessage(null);
};
const handleShowWords = () => {
if (!showWordModal) {
setHintsUsed(prev => prev + 1);
}
setShowWordModal(prev => !prev);
};
const isBubbleSelected = (bubble: Bubble): boolean => {
return selectedBubbles.some(b => b.text === bubble.text && b.word_pl === bubble.word_pl);
};
const isBubbleFound = (bubble: Bubble): boolean => {
return foundWords.includes(bubble.word_pl);
};
const isHintHighlighted = (bubble: Bubble): boolean => {
const key = `${bubble.text}-${bubble.word_pl}`;
return hintHighlightedBubble === key;
};
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>
);
}
return (
<div style={{
minHeight: '100vh',
background: bgColor,
color: textColor,
fontFamily: fonts.main,
padding: '16px',
display: 'flex',
flexDirection: 'column',
position: 'relative',
overflow: 'hidden',
}}>
<div style={{ position: 'fixed', top: '-80px', right: '-60px', width: '260px', height: '260px', borderRadius: '50%', background: palette.bubble, opacity: 0.22, filter: 'blur(90px)', pointerEvents: 'none', zIndex: 0 }} />
<div style={{ position: 'fixed', bottom: '-50px', left: '-40px', width: '220px', height: '220px', borderRadius: '50%', background: brandColor, opacity: 0.16, filter: 'blur(80px)', pointerEvents: 'none', zIndex: 0 }} />
<style>{`
@keyframes bubbleDrop {
0% { transform: translateY(-70vh) scale(0.3); opacity: 0; }
50% { opacity: 1; }
70% { transform: translateY(6px) scale(1.02); }
85% { transform: translateY(-3px) scale(0.98); }
100% { transform: translateY(0) scale(1); opacity: 1; }
}
@keyframes bubbleWobble {
0%, 100% { transform: translateY(0); }
50% { transform: translateY(-6px); }
}
@keyframes hintPulse {
0%, 100% { box-shadow: 0 0 10px rgba(255, 215, 0, 0.6); }
50% { box-shadow: 0 0 25px rgba(255, 215, 0, 1); }
}
@keyframes fadeInUp {
0% { transform: translateY(10px); opacity: 0; }
100% { transform: translateY(0); opacity: 1; }
}
@keyframes messagePopIn {
0% { opacity: 0; transform: translateX(-50%) translateY(-10px); }
100% { opacity: 1; transform: translateX(-50%) translateY(0); }
}
@keyframes achievementSlideDown {
0% { transform: translateX(-50%) translateY(-80px); opacity: 0; }
100% { transform: translateX(-50%) translateY(0); opacity: 1; }
}
`}</style>
<div style={{ position: 'relative', zIndex: 1, display: 'flex', flexDirection: 'column', flex: 1 }}>
<RulesModal
isOpen={showRules}
onClose={() => setShowRules(false)}
title={t('bubbleWordsRulesTitle') || '🫧 Bubble Words Rules'}
content={t('bubbleWordsRulesContent') || 'Rules content loading...'}
/>
{activeAchievement && (
<div style={{
position: 'fixed',
top: '16px',
left: '50%',
transform: 'translateX(-50%)',
zIndex: 900,
background: 'linear-gradient(135deg, #FFD700, #FFA500)',
color: '#FFFFFF',
padding: '14px 20px',
borderRadius: radius.lg,
boxShadow: '0 8px 30px rgba(255, 215, 0, 0.5)',
display: 'flex',
alignItems: 'center',
gap: '12px',
minWidth: '250px',
maxWidth: '90vw',
animation: 'achievementSlideDown 0.4s ease',
}}>
<span style={{ fontSize: '28px', flexShrink: 0 }}>{activeAchievement.icon}</span>
<div>
<div style={{ fontSize: '11px', fontWeight: 600, opacity: 0.9, letterSpacing: '1px', textTransform: 'uppercase' }}>
🏆 {t('achievement') || 'Achievement'}
</div>
<div style={{ fontSize: '15px', fontWeight: 800, marginTop: '2px' }}>
{activeAchievement.name}
</div>
</div>
</div>
)}
<div style={{
display: 'flex',
justifyContent: 'space-between',
alignItems: 'center',
marginBottom: '16px',
animation: 'fadeInUp 0.3s ease',
}}>
<div style={{ display: 'flex', gap: '8px', alignItems: 'center' }}>
<button
onClick={() => navigate('/menu')}
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>
<button
onClick={() => setShowRules(true)}
style={{
...glass({
width: '40px',
height: '40px',
borderRadius: radius.md,
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
}),
color: textColor,
fontSize: '18px',
fontWeight: 700,
cursor: 'pointer',
transition: 'transform 0.2s ease',
flexShrink: 0,
}}
onTouchStart={(e) => { e.currentTarget.style.transform = 'scale(0.95)'; }}
onTouchEnd={(e) => { e.currentTarget.style.transform = 'scale(1)'; }}
>
?
</button>
</div>
<div style={{ textAlign: 'center' }}>
<div style={{ fontSize: '14px', color: subColor }}>
{t('level')} {bubbleLevel}
</div>
</div>
<div style={{ textAlign: 'right', display: 'flex', alignItems: 'center', gap: '8px' }}>
<span style={{
fontSize: '12px',
fontWeight: 800,
color: brandColor,
background: `${brandColor}15`,
padding: '4px 8px',
borderRadius: radius.sm,
border: `1px solid ${brandColor}40`,
}}>
{currentLevel}
</span>
<div>
<div style={{ fontSize: '11px', color: subColor, marginBottom: '2px' }}>
{t('score')}
</div>
<div style={{
fontSize: '16px',
fontWeight: 800,
color: brandColor,
}}>
{totalScore}
</div>
</div>
</div>
</div>
{errorMessage && (
<div style={{
position: 'absolute',
top: '60px',
left: '50%',
transform: 'translateX(-50%)',
padding: '10px 20px',
fontSize: '14px',
fontWeight: 600,
color: '#FFFFFF',
background: '#F39C12',
borderRadius: radius.md,
boxShadow: '0 4px 12px rgba(243,156,18,0.4)',
whiteSpace: 'nowrap',
zIndex: 10,
animation: 'messagePopIn 0.25s ease',
}}>
{errorMessage}
</div>
)}
{message && (
<div style={{
position: 'absolute',
top: '60px',
left: '50%',
transform: 'translateX(-50%)',
padding: '10px 20px',
fontSize: '16px',
fontWeight: 700,
color: '#FFFFFF',
background: brandColor,
borderRadius: radius.md,
boxShadow: `0 4px 12px ${brandColor}40`,
whiteSpace: 'nowrap',
zIndex: 10,
animation: 'messagePopIn 0.25s ease',
pointerEvents: 'none',
}}>
{message}
</div>
)}
<div style={{
display: 'flex',
flexWrap: 'wrap',
gap: '6px',
marginBottom: '12px',
minHeight: '24px',
animation: 'fadeInUp 0.3s ease',
}}>
{foundWords.map(w => (
<span key={w} style={{
padding: '4px 10px',
borderRadius: radius.sm,
background: `${brandColor}20`,
color: '#1a7a3a',
fontSize: '12px',
fontWeight: 700,
border: `1px solid ${brandColor}40`,
}}>
✅ {w}
</span>
))}
</div>
<div style={{
flex: 1,
display: 'flex',
flexWrap: 'wrap',
gap: '10px',
justifyContent: 'center',
alignContent: 'flex-start',
padding: '10px 0',
overflow: 'auto',
position: 'relative',
}}>
{bubbles.map((bubble, index) => {
const selected = isBubbleSelected(bubble);
const found = isBubbleFound(bubble);
const hinted = isHintHighlighted(bubble);
if (found) return null;
const totalBubbles = bubbles.length;
const isSmallLevel = totalBubbles <= 12;
const bubbleSize = isSmallLevel
? (bubble.text.length <= 2 ? 70 : bubble.text.length <= 3 ? 80 : 90)
: (bubble.text.length <= 2 ? 55 : bubble.text.length <= 3 ? 65 : 75);
return (
<div
key={`${bubble.text}-${bubble.word_pl}-${index}`}
onClick={() => handleBubbleClick(bubble)}
style={{
width: bubbleSize,
height: bubbleSize,
borderRadius: '50%',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
fontSize: bubbleSize > 70 ? '17px' : bubbleSize > 60 ? '15px' : '14px',
fontWeight: 700,
cursor: 'pointer',
userSelect: 'none',
transition: 'all 0.2s ease',
background: hinted
? 'radial-gradient(circle at 35% 35%, #FFD700, #FFA500)'
: selected
? `radial-gradient(circle at 35% 35%, ${palette.bubble}CC, ${palette.bubble})`
: 'rgba(255,255,255,0.55)',
border: hinted
? '3px solid #FFD700'
: selected
? `2px solid ${palette.bubble}`
: '1px solid rgba(0,0,0,0.06)',
color: hinted ? '#FFFFFF' : selected ? '#FFFFFF' : textColor,
boxShadow: hinted
? '0 0 20px rgba(255, 215, 0, 0.8)'
: selected
? `0 0 15px ${palette.bubble}60`
: '0 4px 12px rgba(31,38,73,0.06)',
animation: hinted
? `bubbleDrop 0.7s cubic-bezier(0.34, 1.56, 0.64, 1) ${index * 0.1}s both, hintPulse 0.8s ease-in-out infinite`
: animationsReady
? `bubbleDrop 0.7s cubic-bezier(0.34, 1.56, 0.64, 1) ${index * 0.1}s both, bubbleWobble ${2.5 + index * 0.4}s ease-in-out infinite ${0.7 + index * 0.1}s`
: 'none',
opacity: animationsReady ? 1 : 0,
}}
onTouchStart={(e) => { e.currentTarget.style.transform = 'scale(0.9)'; }}
onTouchEnd={(e) => { e.currentTarget.style.transform = 'scale(1)'; }}
>
{bubble.text}
</div>
);
})}
</div>
{selectedBubbles.length > 0 && (
<div style={{
display: 'flex',
flexWrap: 'wrap',
gap: '6px',
justifyContent: 'center',
padding: '8px',
marginBottom: '8px',
background: 'rgba(0,0,0,0.02)',
borderRadius: radius.md,
border: '1px dashed rgba(0,0,0,0.1)',
animation: 'fadeInUp 0.2s ease',
}}>
{selectedBubbles.map((b, i) => (
<span key={i} style={{
padding: '6px 10px',
borderRadius: radius.sm,
background: `${palette.bubble}20`,
color: palette.bubble,
fontSize: '14px',
fontWeight: 700,
border: `1px solid ${palette.bubble}40`,
}}>
{b.text}
</span>
))}
</div>
)}
<div style={{
display: 'flex',
gap: '10px',
justifyContent: 'center',
padding: '8px 0',
animation: 'fadeInUp 0.3s ease 0.2s both',
}}>
<button
onClick={handleFirstLetterHint}
disabled={firstLetterHintsUsed >= maxFirstLetterHints}
style={{
...glass({
flex: 1,
padding: '12px',
borderRadius: radius.md,
display: 'flex',
flexDirection: 'column',
alignItems: 'center',
gap: '6px',
}),
opacity: firstLetterHintsUsed >= maxFirstLetterHints ? 0.5 : 1,
cursor: firstLetterHintsUsed >= maxFirstLetterHints ? 'default' : 'pointer',
fontSize: '13px',
fontWeight: 600,
color: textColor,
}}
onTouchStart={(e) => { if (firstLetterHintsUsed < maxFirstLetterHints) e.currentTarget.style.transform = 'scale(0.95)'; }}
onTouchEnd={(e) => { e.currentTarget.style.transform = 'scale(1)'; }}
>
<span>💡 {t('firstLetter')}</span>
<div style={{ display: 'flex', gap: '6px' }}>
{Array.from({ length: maxFirstLetterHints }, (_, i) => (
<div key={i} style={{
width: '10px',
height: '10px',
borderRadius: '50%',
background: i < maxFirstLetterHints - firstLetterHintsUsed ? brandColor : 'rgba(0,0,0,0.08)',
border: i < maxFirstLetterHints - firstLetterHintsUsed ? `1px solid ${brandColor}` : '1px solid rgba(0,0,0,0.06)',
boxShadow: i < maxFirstLetterHints - firstLetterHintsUsed ? `0 0 6px ${brandColor}80` : 'inset 0 1px 2px rgba(0,0,0,0.06)',
}} />
))}
</div>
</button>
<button
onClick={handleShowWords}
style={{
...glass({
flex: 1,
padding: '12px',
borderRadius: radius.md,
display: 'flex',
flexDirection: 'column',
alignItems: 'center',
gap: '6px',
}),
border: showWordModal ? `2px solid ${brandColor}` : '1px solid rgba(255,255,255,0.7)',
fontSize: '13px',
fontWeight: 600,
color: textColor,
cursor: 'pointer',
}}
onTouchStart={(e) => { e.currentTarget.style.transform = 'scale(0.95)'; }}
onTouchEnd={(e) => { e.currentTarget.style.transform = 'scale(1)'; }}
>
<span>📖 {t('showWords')} {showWordModal ? '▲' : '▼'}</span>
<span style={{ fontSize: '18px', color: brandColor, lineHeight: '1' }}>∞</span>
</button>
</div>
{showWordModal && (
<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) setShowWordModal(false); }}
>
<div style={{
...glass({
borderRadius: radius.lg,
padding: '20px',
width: '100%',
maxWidth: '400px',
maxHeight: '70vh',
overflow: 'auto',
}),
boxShadow: '0 20px 60px rgba(31,38,73,0.20), inset 0 1px 0 rgba(255,255,255,0.85)',
}}>
<div style={{
display: 'flex',
justifyContent: 'space-between',
alignItems: 'center',
marginBottom: '16px',
paddingBottom: '12px',
borderBottom: '1px solid rgba(0,0,0,0.06)',
}}>
<h3 style={{ margin: 0, fontSize: '18px', fontWeight: 700, color: textColor }}>📖 {t('showWords')}</h3>
<button
onClick={() => setShowWordModal(false)}
style={{
...glass({
padding: '8px 16px',
borderRadius: radius.md,
}),
color: textColor,
fontSize: '14px',
fontWeight: 600,
cursor: 'pointer',
}}
>
✕
</button>
</div>
<div style={{ display: 'flex', flexWrap: 'wrap', gap: '10px', justifyContent: 'center' }}>
{words.map(w => (
<div key={w.word_pl} style={{
padding: '10px 14px',
borderRadius: radius.md,
background: foundWords.includes(w.word_pl) ? `${brandColor}20` : 'rgba(255,255,255,0.55)',
border: `2px solid ${foundWords.includes(w.word_pl) ? brandColor : 'rgba(0,0,0,0.06)'}`,
color: foundWords.includes(w.word_pl) ? '#1a7a3a' : textColor,
fontSize: '14px',
fontWeight: foundWords.includes(w.word_pl) ? 700 : 400,
display: 'flex',
flexDirection: 'column',
alignItems: 'center',
gap: '4px',
minWidth: '80px',
}}>
<span style={{ fontSize: '16px' }}>{w.word_pl}</span>
{w.translation && (
<span style={{ fontSize: '11px', color: foundWords.includes(w.word_pl) ? brandColor : subColor }}>
{w.translation}
</span>
)}
{foundWords.includes(w.word_pl) && <span style={{ fontSize: '12px' }}>✅</span>}
</div>
))}
</div>
<div style={{
marginTop: '16px',
paddingTop: '12px',
borderTop: '1px solid rgba(0,0,0,0.06)',
textAlign: 'center',
fontSize: '14px',
color: subColor,
}}>
{foundWords.length}/{words.length} {t('foundWords').toLowerCase()}
</div>
</div>
</div>
)}
{completed && (
<div style={{
textAlign: 'center',
padding: '16px',
marginTop: '8px',
background: `${brandColor}15`,
borderRadius: radius.lg,
border: `2px solid ${brandColor}40`,
}}>
<div style={{ fontSize: '28px', marginBottom: '4px' }}>🎉</div>
<div style={{ fontSize: '16px', fontWeight: 700, color: brandColor }}>{t('levelCompleted')}</div>
</div>
)}
<div style={{ textAlign: 'center', marginTop: '8px', color: subColor, fontSize: '12px' }}>
{t('levelsCompleted')}: {levelsCompleted}
</div>
</div>
</div>
);
};
export default BubbleWordsPage;
+711
View File
@@ -0,0 +1,711 @@
import { useState, useEffect, useRef } from 'react';
import { useNavigate } from 'react-router-dom';
import { useLanguage } from '../i18n/LanguageContext';
import { fonts, radius } from '../styles/theme';
import { polishAlphabet } from '../data/alphabet';
import { polishDiacritics } from '../data/diacritics';
import { grammarRules } from '../data/grammarRules';
import { cheatsheets } from '../data/cheatsheets';
// 🔧 ИСПРАВЛЕНО: Убран trackFlashcardsOpened
import { trackCheatsheetsOpened, trackAlphabetOpened, trackRulesOpened, getTTS } from '../api';
import { useAchievements } from '../hooks/useAchievements';
type TabType = 'alphabet' | 'grammar' | 'cheatsheets';
const tabColors: Record<TabType, string> = {
alphabet: '#2ECC71',
grammar: '#E74C3C',
cheatsheets: '#A970D6',
};
const FlashcardsPage: React.FC = () => {
const navigate = useNavigate();
const { t, language } = useLanguage();
const [activeTab, setActiveTab] = useState<TabType>('alphabet');
const [selectedRule, setSelectedRule] = useState<number | null>(null);
const [selectedCheatSheet, setSelectedCheatSheet] = useState<string | null>(null);
const [selectedLetter, setSelectedLetter] = useState<number | null>(null);
const [isPlayingLetter, setIsPlayingLetter] = useState(false);
const { activeAchievement, showAchievement } = useAchievements();
const isMountedRef = useRef(true);
const audioRef = useRef<HTMLAudioElement | 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,
});
const tabs: { key: TabType; icon: string; label_pl: string; label_ru: string; label_uk: string; label_en: string }[] = [
{ key: 'alphabet', icon: '🔤', label_pl: 'Alfabet', label_ru: 'Алфавит', label_uk: 'Алфавіт', label_en: 'Alphabet' },
{ key: 'grammar', icon: '📐', label_pl: 'Zasady', label_ru: 'Правила', label_uk: 'Правила', label_en: 'Grammar' },
{ key: 'cheatsheets', icon: '📝', label_pl: 'Ściągi', label_ru: 'Шпаргалки', label_uk: 'Шпаргалки', label_en: 'Cheatsheets' },
];
const getTabLabel = (tab: typeof tabs[0]): string => {
const map: Record<string, string> = { pl: tab.label_pl, ru: tab.label_ru, uk: tab.label_uk, en: tab.label_en };
return map[language] || tab.label_en;
};
const getLocalized = (item: any, field: string): string => {
const key = `${field}_${language}`;
return item[key] || item[`${field}_en`] || '';
};
const getLocalizedExample = (item: any): string => {
const key = `example_${language}`;
return item[key] || item.example_en || '';
};
const getDiacriticInfo = (letter: string): { pronunciation: string; description: string } | null => {
const found = polishDiacritics.find(d => d.letter.includes(letter));
if (!found) return null;
return {
pronunciation: found.pronunciation,
description: getLocalized(found, 'description'),
};
};
const playLetterSound = async (word: string) => {
if (audioRef.current) {
audioRef.current.pause();
audioRef.current = null;
}
if ('speechSynthesis' in window) {
window.speechSynthesis.cancel();
}
setIsPlayingLetter(true);
try {
const audioBlob = await getTTS(word, 'male');
const audioUrl = URL.createObjectURL(audioBlob);
const audio = new Audio(audioUrl);
audioRef.current = audio;
audio.onended = () => {
if (isMountedRef.current) setIsPlayingLetter(false);
};
audio.onerror = () => {
playWebSpeech(word);
};
await audio.play();
} catch (e) {
console.error('Edge TTS error:', e);
playWebSpeech(word);
}
};
const playWebSpeech = (word: string) => {
if ('speechSynthesis' in window) {
const utterance = new SpeechSynthesisUtterance(word);
utterance.lang = 'pl-PL';
utterance.onend = () => {
if (isMountedRef.current) setIsPlayingLetter(false);
};
utterance.onerror = () => {
if (isMountedRef.current) setIsPlayingLetter(false);
};
window.speechSynthesis.speak(utterance);
} else {
if (isMountedRef.current) setIsPlayingLetter(false);
}
};
useEffect(() => {
window.scrollTo(0, 0);
isMountedRef.current = true;
// 🔧 ИСПРАВЛЕНО: Трекинг только для Алфавита (активная вкладка по умолчанию)
trackAlphabetOpened()
.then((data: any) => {
if (data?.new_achievements && data.new_achievements.length > 0) {
data.new_achievements.forEach((ach: any) => {
showAchievement({
id: ach.code,
icon: ach.icon,
name: ach.name,
});
});
}
})
.catch(() => {});
return () => {
isMountedRef.current = false;
if (audioRef.current) {
audioRef.current.pause();
audioRef.current = null;
}
if ('speechSynthesis' in window) {
window.speechSynthesis.cancel();
}
};
}, [showAchievement]);
// 🔧 ИСПРАВЛЕНО: switchTab теперь сбрасывает window scroll
const switchTab = (tab: TabType) => {
setActiveTab(tab);
setSelectedRule(null);
setSelectedCheatSheet(null);
setSelectedLetter(null);
window.scrollTo(0, 0);
if (tab === 'cheatsheets') {
trackCheatsheetsOpened()
.then((data: any) => {
if (data?.new_achievements && data.new_achievements.length > 0) {
data.new_achievements.forEach((ach: any) => {
showAchievement({
id: ach.code,
icon: ach.icon,
name: ach.name,
});
});
}
})
.catch(() => {});
}
if (tab === 'grammar') {
trackRulesOpened()
.then((data: any) => {
if (data?.new_achievements && data.new_achievements.length > 0) {
data.new_achievements.forEach((ach: any) => {
showAchievement({
id: ach.code,
icon: ach.icon,
name: ach.name,
});
});
}
})
.catch(() => {});
}
};
const getCloseLabel = (): string => {
const labels: Record<string, string> = {
pl: 'Zamknij',
ru: 'Закрыть',
uk: 'Закрити',
en: 'Close',
};
return labels[language] || labels.en;
};
const renderAlphabet = () => (
<div style={{ animation: 'fadeInUp 0.3s ease' }}>
<p style={{ textAlign: 'center', color: subColor, fontSize: '14px', marginBottom: '16px' }}>
{language === 'pl' ? 'Kliknij na literę, aby zobaczyć szczegóły i usłyszeć wymowę' :
language === 'ru' ? 'Нажми на букву, чтобы увидеть детали и услышать произношение' :
language === 'uk' ? 'Натисни на літеру, щоб побачити деталі та почути вимову' :
'Tap a letter to see details and hear pronunciation'}
</p>
<div style={{
display: 'grid',
gridTemplateColumns: 'repeat(auto-fill, minmax(60px, 1fr))',
gap: '8px',
}}>
{polishAlphabet.map((letter, i) => {
const isDiacritic = polishDiacritics.some(d => d.letter.includes(letter.upper));
return (
<button
key={i}
onClick={() => setSelectedLetter(i)}
style={{
...glass({
padding: '14px 8px',
borderRadius: radius.md,
display: 'flex',
flexDirection: 'column',
alignItems: 'center',
gap: '2px',
}),
color: textColor,
fontSize: '20px',
fontWeight: 700,
cursor: 'pointer',
transition: 'all 0.2s ease',
border: isDiacritic ? `2px solid ${tabColors.alphabet}50` : '1px solid rgba(255,255,255,0.7)',
}}
onTouchStart={(e) => { e.currentTarget.style.transform = 'scale(0.95)'; }}
onTouchEnd={(e) => { e.currentTarget.style.transform = 'scale(1)'; }}
>
<span style={{ fontSize: '22px' }}>{letter.upper}</span>
<span style={{ fontSize: '10px', color: subColor }}>{letter.lower}</span>
</button>
);
})}
</div>
{selectedLetter !== null && (() => {
const letter = polishAlphabet[selectedLetter];
const diacriticInfo = getDiacriticInfo(letter.upper);
return (
<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',
animation: 'modalFadeIn 0.2s ease', padding: '20px',
backdropFilter: 'blur(4px)', WebkitBackdropFilter: 'blur(4px)',
}}
onClick={(e) => { if (e.target === e.currentTarget) setSelectedLetter(null); }}
>
<div style={{
...glass({
borderRadius: radius.lg,
padding: '24px',
width: '100%',
maxWidth: '360px',
textAlign: 'center',
}),
boxShadow: '0 20px 60px rgba(31,38,73,0.20), inset 0 1px 0 rgba(255,255,255,0.85)',
animation: 'modalSlideUp 0.3s ease',
}}>
<div style={{
fontSize: '72px', fontWeight: 900, color: tabColors.alphabet,
lineHeight: '1', marginBottom: '4px',
}}>
{letter.upper} <span style={{ fontSize: '56px' }}>{letter.lower}</span>
</div>
<div style={{
fontSize: '16px', color: textColor, fontWeight: 700,
marginBottom: '12px', padding: '8px 16px',
background: `${tabColors.alphabet}15`, borderRadius: radius.md,
display: 'inline-block',
}}>
{language === 'pl' ? 'Wymowa' : language === 'ru' ? 'Произношение' : language === 'uk' ? 'Вимова' : 'Pronunciation'}: {diacriticInfo ? diacriticInfo.pronunciation : getLocalized(letter, 'pronunciation')}
</div>
{diacriticInfo && (
<div style={{
padding: '12px',
background: `${tabColors.alphabet}10`,
borderRadius: radius.md,
marginBottom: '12px',
fontSize: '13px',
color: subColor,
lineHeight: '1.5',
textAlign: 'left',
border: `1px solid ${tabColors.alphabet}30`,
}}>
{diacriticInfo.description}
</div>
)}
<div style={{
padding: '16px', background: 'rgba(0,0,0,0.02)',
borderRadius: radius.md, marginBottom: '16px', textAlign: 'left',
cursor: 'pointer',
transition: 'all 0.2s ease',
border: isPlayingLetter ? `2px solid ${tabColors.alphabet}50` : '2px solid transparent',
}}
onClick={() => playLetterSound(letter.example_pl)}
onTouchStart={(e) => { e.currentTarget.style.transform = 'scale(0.98)'; }}
onTouchEnd={(e) => { e.currentTarget.style.transform = 'scale(1)'; }}
>
<div style={{ fontSize: '18px', fontWeight: 700, color: textColor, marginBottom: '6px', display: 'flex', alignItems: 'center', gap: '8px' }}>
🇵🇱 {letter.example_pl}
<span style={{
fontSize: '16px',
color: tabColors.alphabet,
animation: isPlayingLetter ? 'pulse 0.5s ease infinite' : 'none',
display: 'inline-block',
}}>
🔊
</span>
</div>
<div style={{ fontSize: '13px', color: subColor }}>
{getLocalizedExample(letter)}
</div>
<div style={{ fontSize: '10px', color: tabColors.alphabet, marginTop: '6px', fontWeight: 600 }}>
{isPlayingLetter
? (language === 'pl' ? 'Odtwarzanie...' : language === 'ru' ? 'Воспроизведение...' : language === 'uk' ? 'Відтворення...' : 'Playing...')
: (language === 'pl' ? 'Kliknij aby usłyszeć' : language === 'ru' ? 'Нажми чтобы услышать' : language === 'uk' ? 'Натисни щоб почути' : 'Tap to hear')}
</div>
</div>
<button
onClick={() => {
setSelectedLetter(null);
setIsPlayingLetter(false);
}}
style={{
...glass({
padding: '12px 24px',
borderRadius: radius.md,
}),
color: textColor,
fontSize: '14px',
fontWeight: 600,
cursor: 'pointer',
width: '100%',
transition: 'transform 0.2s ease',
}}
onTouchStart={(e) => { e.currentTarget.style.transform = 'scale(0.96)'; }}
onTouchEnd={(e) => { e.currentTarget.style.transform = 'scale(1)'; }}
>
{getCloseLabel()}
</button>
</div>
</div>
);
})()}
</div>
);
const renderGrammar = () => (
<div style={{ display: 'flex', flexDirection: 'column', gap: '12px', animation: 'fadeInUp 0.3s ease' }}>
{grammarRules.map((rule: any) => (
<div key={rule.id} style={{
...glass({
padding: '16px',
borderRadius: radius.lg,
}),
cursor: 'pointer',
transition: 'all 0.2s ease',
}} onClick={() => setSelectedRule(rule.id)}>
<div style={{ fontSize: '16px', fontWeight: 700, color: tabColors.grammar }}>
{getLocalized(rule, 'title')}
</div>
</div>
))}
{selectedRule !== null && (() => {
const rule = grammarRules.find((r: any) => r.id === selectedRule);
if (!rule) return null;
return (
<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',
animation: 'modalFadeIn 0.2s ease', padding: '20px',
backdropFilter: 'blur(4px)', WebkitBackdropFilter: 'blur(4px)',
}}
onClick={(e) => { if (e.target === e.currentTarget) setSelectedRule(null); }}
>
<div style={{
...glass({
borderRadius: radius.lg,
padding: '24px',
width: '100%',
maxWidth: '420px',
maxHeight: '80vh',
overflow: 'auto',
}),
boxShadow: '0 24px 60px rgba(31,38,73,0.20), inset 0 1px 0 rgba(255,255,255,0.85)',
animation: 'modalSlideUp 0.3s ease',
}}>
<h3 style={{
margin: '0 0 12px 0',
fontSize: '18px',
fontWeight: 700,
color: tabColors.grammar,
}}>
📐 {getLocalized(rule, 'title')}
</h3>
<div style={{ width: 'calc(100% - 32px)', height: '2px', background: `${tabColors.grammar}25`, borderRadius: '1px', margin: '0 16px 16px 16px' }} />
<p style={{
fontSize: '14px',
color: textColor,
lineHeight: '1.7',
marginBottom: '16px',
whiteSpace: 'pre-line',
}}>
{getLocalized(rule, 'description').replace(/\\n/g, '\n')}
</p>
<div style={{
padding: '14px',
background: `${tabColors.grammar}10`,
borderRadius: radius.md,
border: `1px solid ${tabColors.grammar}30`,
fontSize: '14px',
lineHeight: '1.6',
marginBottom: '20px',
}}>
{language === 'pl' ? (
<div style={{ fontWeight: 700, color: textColor, whiteSpace: 'pre-line' }}>
{rule.example_pl.replace(/\\n/g, '\n')}
</div>
) : (
<div style={{ color: textColor, fontSize: '14px', lineHeight: '1.6', whiteSpace: 'pre-line' }}>
{getLocalized(rule, 'example').replace(/\\n/g, '\n')}
</div>
)}
</div>
<button
onClick={() => setSelectedRule(null)}
style={{
...glass({
padding: '12px 24px',
borderRadius: radius.md,
}),
color: textColor,
fontSize: '14px',
fontWeight: 600,
cursor: 'pointer',
width: '100%',
transition: 'transform 0.2s ease',
}}
onTouchStart={(e) => { e.currentTarget.style.transform = 'scale(0.96)'; }}
onTouchEnd={(e) => { e.currentTarget.style.transform = 'scale(1)'; }}
>
{getCloseLabel()}
</button>
</div>
</div>
);
})()}
</div>
);
const renderCheatsheets = () => (
<div style={{ display: 'flex', flexDirection: 'column', gap: '12px', animation: 'fadeInUp 0.3s ease' }}>
{cheatsheets.map((section) => (
<div key={section.id} style={{
...glass({
padding: '16px',
borderRadius: radius.lg,
}),
cursor: 'pointer',
transition: 'all 0.2s ease',
}} onClick={() => setSelectedCheatSheet(section.id)}>
<div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
<span style={{ fontSize: '20px' }}>{section.icon}</span>
<span style={{ fontSize: '16px', fontWeight: 700, color: tabColors.cheatsheets }}>
{getLocalized(section, 'title')}
</span>
</div>
</div>
))}
{selectedCheatSheet !== null && (() => {
const section = cheatsheets.find(s => s.id === selectedCheatSheet);
if (!section) return null;
return (
<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',
animation: 'modalFadeIn 0.2s ease', padding: '20px',
backdropFilter: 'blur(4px)', WebkitBackdropFilter: 'blur(4px)',
}}
onClick={(e) => { if (e.target === e.currentTarget) setSelectedCheatSheet(null); }}
>
<div style={{
...glass({
borderRadius: radius.lg,
padding: '24px',
width: '100%',
maxWidth: '420px',
maxHeight: '80vh',
overflow: 'auto',
}),
boxShadow: '0 24px 60px rgba(31,38,73,0.20), inset 0 1px 0 rgba(255,255,255,0.85)',
animation: 'modalSlideUp 0.3s ease',
}}>
<h3 style={{
margin: '0 0 16px 0',
fontSize: '18px',
fontWeight: 700,
color: tabColors.cheatsheets,
display: 'flex',
alignItems: 'center',
gap: '8px',
}}>
<span>{section.icon}</span>
<span>{getLocalized(section, 'title')}</span>
</h3>
<div style={{ width: 'calc(100% - 32px)', height: '2px', background: `${tabColors.cheatsheets}25`, borderRadius: '1px', margin: '0 16px 16px 16px' }} />
<div style={{ display: 'flex', flexDirection: 'column', gap: '12px', marginBottom: '20px' }}>
{section.items.map((item, i) => {
const content = language === 'pl' ? item.pl : (item[language as keyof typeof item] || item.en || item.pl);
return (
<div key={i} style={{
padding: '14px',
background: i % 2 === 0 ? 'rgba(0,0,0,0.02)' : 'transparent',
borderRadius: radius.md,
fontSize: '13px',
lineHeight: '1.8',
whiteSpace: 'pre-line',
color: textColor,
border: '1px solid rgba(0,0,0,0.04)',
}}>
{content}
</div>
);
})}
</div>
<button
onClick={() => setSelectedCheatSheet(null)}
style={{
...glass({
padding: '12px 24px',
borderRadius: radius.md,
}),
color: textColor,
fontSize: '14px',
fontWeight: 600,
cursor: 'pointer',
width: '100%',
transition: 'transform 0.2s ease',
}}
onTouchStart={(e) => { e.currentTarget.style.transform = 'scale(0.96)'; }}
onTouchEnd={(e) => { e.currentTarget.style.transform = 'scale(1)'; }}
>
{getCloseLabel()}
</button>
</div>
</div>
);
})()}
</div>
);
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: tabColors[activeTab], opacity: 0.18, filter: 'blur(90px)', pointerEvents: 'none', zIndex: 0 }} />
<div style={{ position: 'fixed', bottom: '-50px', left: '-40px', width: '240px', height: '240px', borderRadius: '50%', background: brandColor, opacity: 0.14, filter: 'blur(80px)', pointerEvents: 'none', zIndex: 0 }} />
<style>{`
@keyframes fadeInUp {
0% { transform: translateY(10px); opacity: 0; }
100% { transform: translateY(0); opacity: 1; }
}
@keyframes achievementSlideDown {
0% { transform: translateX(-50%) translateY(-80px); opacity: 0; }
100% { transform: translateX(-50%) translateY(0); opacity: 1; }
}
@keyframes modalFadeIn {
0% { opacity: 0; }
100% { opacity: 1; }
}
@keyframes modalSlideUp {
0% { transform: translateY(30px); opacity: 0; }
100% { transform: translateY(0); opacity: 1; }
}
@keyframes pulse {
0%, 100% { transform: scale(1); }
50% { transform: scale(1.1); }
}
`}</style>
<div style={{ position: 'relative', zIndex: 1, display: 'flex', flexDirection: 'column', flex: 1 }}>
{activeAchievement && (
<div style={{
position: 'fixed', top: '16px', left: '50%', transform: 'translateX(-50%)', zIndex: 900,
background: 'linear-gradient(135deg, #FFD700, #FFA500)',
color: '#FFFFFF', padding: '14px 20px', borderRadius: radius.lg,
boxShadow: '0 8px 30px rgba(255, 215, 0, 0.5)',
display: 'flex', alignItems: 'center', gap: '12px',
minWidth: '250px', maxWidth: '90vw', animation: 'achievementSlideDown 0.4s ease',
}}>
<span style={{ fontSize: '28px', flexShrink: 0 }}>{activeAchievement.icon}</span>
<div>
<div style={{ fontSize: '11px', fontWeight: 600, opacity: 0.9, letterSpacing: '1px', textTransform: 'uppercase' }}>
🏆 {t('achievement') || 'Achievement'}
</div>
<div style={{ fontSize: '15px', fontWeight: 800, marginTop: '2px' }}>
{activeAchievement.name}
</div>
</div>
</div>
)}
<div style={{ marginBottom: '12px', animation: 'fadeInUp 0.3s ease' }}>
<button
onClick={() => navigate('/menu')}
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>
</div>
<div style={{
display: 'flex', gap: '6px', marginBottom: '20px', overflow: 'auto',
WebkitOverflowScrolling: 'touch', paddingBottom: '4px',
animation: 'fadeInUp 0.3s ease 0.05s both',
}}>
{tabs.map((tab) => (
<button
key={tab.key}
onClick={() => switchTab(tab.key)}
style={{
padding: '10px 14px',
borderRadius: radius.md,
border: activeTab === tab.key ? `2px solid ${tabColors[tab.key]}` : '1px solid rgba(255,255,255,0.7)',
background: activeTab === tab.key ? `${tabColors[tab.key]}18` : cardBg,
backdropFilter: 'blur(24px) saturate(180%)',
WebkitBackdropFilter: 'blur(24px) saturate(180%)',
color: activeTab === tab.key ? tabColors[tab.key] : textColor,
fontSize: '13px',
fontWeight: 600,
cursor: 'pointer',
whiteSpace: 'nowrap',
flexShrink: 0,
boxShadow: activeTab === tab.key ? `0 0 10px ${tabColors[tab.key]}30` : '0 2px 8px rgba(31,38,73,0.06)',
transition: 'all 0.2s ease',
}}
>
{tab.icon} {getTabLabel(tab)}
</button>
))}
</div>
<div style={{ flex: 1 }}>
{activeTab === 'alphabet' && renderAlphabet()}
{activeTab === 'grammar' && renderGrammar()}
{activeTab === 'cheatsheets' && renderCheatsheets()}
</div>
</div>
</div>
);
};
export default FlashcardsPage;
+109
View File
@@ -0,0 +1,109 @@
import { useNavigate } from 'react-router-dom';
import { useLanguage } from '../i18n/LanguageContext';
import { fonts, radius } from '../styles/theme';
const languages = [
{ code: 'pl', name: 'Polski', flag: '🇵🇱' },
{ code: 'ru', name: 'Русский', flag: '🇷🇺' },
{ code: 'uk', name: 'Українська', flag: '🇺🇦' },
{ code: 'en', name: 'English', flag: '🇬🇧' },
];
const LanguageSelectPage: React.FC = () => {
const navigate = useNavigate();
const { setLang } = useLanguage();
const handleSelect = (code: string) => {
setLang(code);
navigate('/menu');
};
return (
<div style={{
minHeight: '100vh',
background: '#F4F5F7',
color: '#1A1A2E',
fontFamily: fonts.main,
display: 'flex',
flexDirection: 'column',
alignItems: 'center',
justifyContent: 'center',
padding: '24px',
position: 'relative',
overflow: 'hidden',
}}>
<div style={{ position: 'fixed', top: '-120px', left: '-90px', width: '320px', height: '320px', borderRadius: '50%', background: '#2ECC71', opacity: 0.25, filter: 'blur(90px)', pointerEvents: 'none', zIndex: 0 }} />
<div style={{ position: 'fixed', bottom: '-80px', right: '-60px', width: '280px', height: '280px', borderRadius: '50%', background: '#4FA9E8', opacity: 0.20, filter: 'blur(90px)', pointerEvents: 'none', zIndex: 0 }} />
<style>{`
@keyframes fadeInUp {
0% { transform: translateY(15px); opacity: 0; }
100% { transform: translateY(0); opacity: 1; }
}
`}</style>
<div style={{ position: 'relative', zIndex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', width: '100%', maxWidth: '340px' }}>
<div style={{ fontSize: '56px', marginBottom: '16px', animation: 'fadeInUp 0.3s ease' }}>🌍</div>
<h1 style={{
fontSize: '24px',
fontWeight: 800,
marginBottom: '8px',
textAlign: 'center',
color: '#1A1A2E',
animation: 'fadeInUp 0.3s ease 0.05s both',
}}>
Wybierz język
</h1>
<p style={{
fontSize: '14px',
color: '#6B7280',
marginBottom: '28px',
textAlign: 'center',
animation: 'fadeInUp 0.3s ease 0.1s both',
}}>
Choose your language / Выберите язык / Оберіть мову
</p>
<div style={{
display: 'flex',
flexDirection: 'column',
gap: '12px',
width: '100%',
animation: 'fadeInUp 0.3s ease 0.15s both',
}}>
{languages.map((lang) => (
<button
key={lang.code}
onClick={() => handleSelect(lang.code)}
style={{
padding: '16px 20px',
borderRadius: radius.lg,
border: '1px solid rgba(255,255,255,0.7)',
background: 'rgba(255,255,255,0.55)',
backdropFilter: 'blur(24px) saturate(180%)',
WebkitBackdropFilter: 'blur(24px) saturate(180%)',
color: '#1A1A2E',
fontSize: '17px',
fontWeight: 600,
cursor: 'pointer',
display: 'flex',
alignItems: 'center',
gap: '14px',
boxShadow: '0 6px 20px rgba(31,38,73,0.08), inset 0 1px 0 rgba(255,255,255,0.85)',
transition: 'all 0.2s ease',
}}
onTouchStart={(e) => { e.currentTarget.style.transform = 'scale(0.96)'; }}
onTouchEnd={(e) => { e.currentTarget.style.transform = 'scale(1)'; }}
>
<span style={{ fontSize: '28px' }}>{lang.flag}</span>
<span>{lang.name}</span>
<span style={{ marginLeft: 'auto', fontSize: '18px', color: '#2ECC71', fontWeight: 800 }}>→</span>
</button>
))}
</div>
</div>
</div>
);
};
export default LanguageSelectPage;
+817
View File
@@ -0,0 +1,817 @@
import { useState, useEffect, useCallback } from 'react';
import { useNavigate } from 'react-router-dom';
import { useLanguage } from '../i18n/LanguageContext';
import { fonts, radius } from '../styles/theme';
import { getLeaderboard, getUserAchievements } from '../api';
import { getUserId } from '../telegram';
interface LeaderboardEntry {
rank: number;
telegram_id: number;
username: string;
total_score: number;
wordsearch_score: number;
sentence_score: number;
wordquiz_score: number;
words_guessed: number;
bubblewords_score: number;
bubble_levels_completed: number;
}
interface MyRank {
rank: number;
telegram_id: number;
total_score: number;
}
interface UserAchievement {
id: number;
code: string;
category: string;
icon: string;
name_pl: string;
name_ru: string;
name_uk: string;
name_en: string;
description_pl: string;
description_ru: string;
description_uk: string;
description_en: string;
unlocked: boolean;
unlocked_at: string | null;
}
const MAX_NAME_LENGTH = 14;
const truncateName = (name: string, maxLen: number = MAX_NAME_LENGTH): string => {
if (!name) return 'Player';
if (name.length <= maxLen) return name;
return name.substring(0, maxLen - 2) + '…';
};
const formatDate = (dateStr: string | null, language: string): string => {
if (!dateStr) return '';
try {
const date = new Date(dateStr);
const locales: Record<string, string> = {
pl: 'pl-PL',
ru: 'ru-RU',
uk: 'uk-UA',
en: 'en-US',
};
return date.toLocaleDateString(locales[language] || 'en-US', {
year: 'numeric',
month: 'long',
day: 'numeric',
});
} catch {
return dateStr;
}
};
interface CategoryConfig {
id: string;
icon: string;
color: string;
bgColor: string;
order: number;
}
const ACHIEVEMENT_CATEGORIES: Record<string, CategoryConfig> = {
wordsearch: {
id: 'wordsearch',
icon: '🔍',
color: '#4FC3F7',
bgColor: 'rgba(79, 195, 247, 0.08)',
order: 1,
},
sentence: {
id: 'sentence',
icon: '📝',
color: '#FF8A65',
bgColor: 'rgba(255, 138, 101, 0.08)',
order: 2,
},
wordquiz: {
id: 'wordquiz',
icon: '🎯',
color: '#BA68C8',
bgColor: 'rgba(186, 104, 200, 0.08)',
order: 3,
},
bubblewords: {
id: 'bubblewords',
icon: '🫧',
color: '#4DD0E1',
bgColor: 'rgba(77, 208, 225, 0.08)',
order: 4,
},
general: {
id: 'general',
icon: '🏆',
color: '#FFD700',
bgColor: 'rgba(255, 215, 0, 0.08)',
order: 5,
},
};
const LeaderboardPage: React.FC = () => {
const navigate = useNavigate();
const { t, language } = useLanguage();
const [entries, setEntries] = useState<LeaderboardEntry[]>([]);
const [myRank, setMyRank] = useState<MyRank | null>(null);
const [achievements, setAchievements] = useState<UserAchievement[]>([]);
const [unlockedCount, setUnlockedCount] = useState(0);
const [totalCount, setTotalCount] = useState(0);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [selectedAchievement, setSelectedAchievement] = useState<UserAchievement | null>(null);
const [showAchievements, setShowAchievements] = useState(false);
const currentUserId = getUserId();
const brandColor = '#2ECC71';
const palette = {
leaderboard: '#E8B93F',
};
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,
});
const fetchData = useCallback(() => {
setLoading(true);
setError(null);
const promises: Promise<any>[] = [
getLeaderboard(50),
getUserAchievements(),
];
Promise.all(promises)
.then((results: any[]) => {
const leaderboardData = results[0];
const achievementsData = results[1];
setEntries(leaderboardData.leaderboard || []);
if (leaderboardData.my_rank) {
setMyRank({
rank: leaderboardData.my_rank.rank,
telegram_id: leaderboardData.my_rank.telegram_id,
total_score: leaderboardData.my_rank.total_score,
});
}
setAchievements(achievementsData.achievements || []);
setUnlockedCount(achievementsData.unlocked || 0);
setTotalCount(achievementsData.total || 0);
})
.catch((err: Error) => {
console.error('Error fetching data:', err);
setError('Failed to load data');
})
.finally(() => setLoading(false));
}, []);
useEffect(() => {
fetchData();
}, [fetchData]);
const getAchievementName = (ach: UserAchievement): string => {
const nameMap: Record<string, string> = {
pl: ach.name_pl,
ru: ach.name_ru,
uk: ach.name_uk,
en: ach.name_en,
};
return nameMap[language] || ach.name_en;
};
const getAchievementDesc = (ach: UserAchievement): string => {
const descMap: Record<string, string> = {
pl: ach.description_pl,
ru: ach.description_ru,
uk: ach.description_uk,
en: ach.description_en,
};
return descMap[language] || ach.description_en;
};
const groupedAchievements = achievements.reduce((acc, ach) => {
const cat = ach.category || 'general';
if (!acc[cat]) {
acc[cat] = [];
}
acc[cat].push(ach);
return acc;
}, {} as Record<string, UserAchievement[]>);
const sortedCategories = Object.keys(groupedAchievements).sort((a, b) => {
const orderA = ACHIEVEMENT_CATEGORIES[a]?.order ?? 99;
const orderB = ACHIEVEMENT_CATEGORIES[b]?.order ?? 99;
return orderA - orderB;
});
const labels: Record<string, string> = {
achievements: language === 'pl' ? 'Osiągnięcia' : language === 'ru' ? 'Достижения' : language === 'uk' ? 'Досягнення' : 'Achievements',
unlocked: language === 'pl' ? 'odblokowano' : language === 'ru' ? 'получено' : language === 'uk' ? 'отримано' : 'unlocked',
unlockedLabel: language === 'pl' ? 'Odblokowano' : language === 'ru' ? 'Получено' : language === 'uk' ? 'Отримано' : 'Unlocked',
lockedLabel: language === 'pl' ? 'Zablokowane' : language === 'ru' ? 'Заблокировано' : language === 'uk' ? 'Заблоковано' : 'Locked',
close: language === 'pl' ? 'Zamknij' : language === 'ru' ? 'Закрыть' : language === 'uk' ? 'Закрити' : 'Close',
showAchievements: language === 'pl' ? 'Pokaż osiągnięcia' : language === 'ru' ? 'Показать достижения' : language === 'uk' ? 'Показати досягнення' : 'Show Achievements',
hideAchievements: language === 'pl' ? 'Ukryj osiągnięcia' : language === 'ru' ? 'Скрыть достижения' : language === 'uk' ? 'Сховати досягнення' : 'Hide Achievements',
categoryWordsearch: language === 'pl' ? '🎮 Filwords' : language === 'ru' ? '🎮 Филворды' : language === 'uk' ? '🎮 Філворди' : '🎮 Word Search',
categorySentence: language === 'pl' ? '📝 Ułóż zdanie' : language === 'ru' ? '📝 Составь предложение' : language === 'uk' ? '📝 Склади речення' : '📝 Sentence Builder',
categoryWordquiz: language === 'pl' ? '🎯 Wybierz słowo' : language === 'ru' ? '🎯 Выбери слово' : language === 'uk' ? '🎯 Вибери слово' : '🎯 Word Match',
categoryBubblewords: language === 'pl' ? '🫧 Bubbles' : language === 'ru' ? '🫧 Пузыри' : language === 'uk' ? '🫧 Бульбашки' : '🫧 Bubbles',
categoryGeneral: language === 'pl' ? '🏆 Ogólne' : language === 'ru' ? '🏆 Общие' : language === 'uk' ? '🏆 Загальні' : '🏆 General',
};
const getCategoryLabel = (categoryId: string): string => {
const keyMap: Record<string, string> = {
wordsearch: 'categoryWordsearch',
sentence: 'categorySentence',
wordquiz: 'categoryWordquiz',
bubblewords: 'categoryBubblewords',
general: 'categoryGeneral',
};
const key = keyMap[categoryId] || 'categoryGeneral';
return labels[key] || categoryId;
};
const getTop3RowStyle = (rank: number): React.CSSProperties => {
if (rank === 1) return {
background: 'linear-gradient(135deg, rgba(255,215,0,0.15), rgba(255,215,0,0.05))',
border: '1px solid rgba(255,215,0,0.3)',
boxShadow: '0 0 15px rgba(255,215,0,0.15)',
};
if (rank === 2) return {
background: 'linear-gradient(135deg, rgba(192,192,192,0.12), rgba(192,192,192,0.04))',
border: '1px solid rgba(192,192,192,0.3)',
boxShadow: '0 0 12px rgba(192,192,192,0.12)',
};
if (rank === 3) return {
background: 'linear-gradient(135deg, rgba(205,127,50,0.12), rgba(205,127,50,0.04))',
border: '1px solid rgba(205,127,50,0.3)',
boxShadow: '0 0 12px rgba(205,127,50,0.12)',
};
return {};
};
const getMedalEmoji = (rank: number): string => {
if (rank === 1) return '🥇';
if (rank === 2) return '🥈';
if (rank === 3) return '🥉';
return '';
};
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 (error) {
return (
<div style={{
minHeight: '100vh',
background: bgColor,
display: 'flex',
flexDirection: 'column',
alignItems: 'center',
justifyContent: 'center',
color: subColor,
fontFamily: fonts.main,
padding: '24px',
}}>
<div style={{ fontSize: '48px', marginBottom: '16px' }}>⚠️</div>
<div style={{ fontSize: '18px', fontWeight: 600, marginBottom: '8px' }}>
{error}
</div>
<button
onClick={fetchData}
style={{
marginTop: '16px',
padding: '12px 24px',
borderRadius: radius.md,
border: 'none',
background: `linear-gradient(180deg, ${brandColor}E6, ${brandColor}CC)`,
color: '#12271C',
fontSize: '14px',
fontWeight: 600,
cursor: 'pointer',
boxShadow: `0 8px 24px ${brandColor}50`,
}}
>
Try Again
</button>
<button
onClick={() => navigate('/menu')}
style={{
marginTop: '12px',
...glass({
padding: '12px 24px',
borderRadius: radius.md,
}),
color: textColor,
fontSize: '14px',
fontWeight: 600,
cursor: 'pointer',
}}
>
← {t('back')}
</button>
</div>
);
}
return (
<div style={{
minHeight: '100vh',
background: bgColor,
color: textColor,
fontFamily: fonts.main,
padding: '24px',
paddingBottom: '40px',
position: 'relative',
overflow: 'hidden',
}}>
<div style={{ position: 'fixed', top: '-80px', right: '-60px', width: '260px', height: '260px', borderRadius: '50%', background: palette.leaderboard, opacity: 0.22, filter: 'blur(90px)', pointerEvents: 'none', zIndex: 0 }} />
<div style={{ position: 'fixed', bottom: '-50px', left: '-40px', width: '240px', height: '240px', borderRadius: '50%', background: brandColor, opacity: 0.16, filter: 'blur(80px)', pointerEvents: 'none', zIndex: 0 }} />
<style>{`
@keyframes fadeInUp {
0% { transform: translateY(10px); opacity: 0; }
100% { transform: translateY(0); opacity: 1; }
}
@keyframes modalFadeIn {
0% { opacity: 0; }
100% { opacity: 1; }
}
@keyframes modalSlideUp {
0% { transform: translateY(30px); opacity: 0; }
100% { transform: translateY(0); opacity: 1; }
}
@keyframes achievementsSlideDown {
0% { max-height: 0; opacity: 0; margin-top: 0; }
100% { max-height: 4000px; opacity: 1; margin-top: 16px; }
}
@keyframes categoryFadeIn {
0% { transform: translateY(8px); opacity: 0; }
100% { transform: translateY(0); opacity: 1; }
}
`}</style>
<div style={{ position: 'relative', zIndex: 1, display: 'flex', flexDirection: 'column' }}>
{/* Модальное окно достижения */}
{selectedAchievement && (
<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',
animation: 'modalFadeIn 0.2s ease', padding: '20px',
backdropFilter: 'blur(4px)', WebkitBackdropFilter: 'blur(4px)',
}}
onClick={(e) => { if (e.target === e.currentTarget) setSelectedAchievement(null); }}
>
<div style={{
...glass({
borderRadius: radius.lg,
padding: '24px',
width: '100%',
maxWidth: '360px',
textAlign: 'center',
}),
boxShadow: '0 20px 60px rgba(31,38,73,0.20), inset 0 1px 0 rgba(255,255,255,0.85)',
animation: 'modalSlideUp 0.3s ease',
}}>
<div style={{ fontSize: '56px', marginBottom: '12px', opacity: selectedAchievement.unlocked ? 1 : 0.4 }}>
{selectedAchievement.unlocked ? selectedAchievement.icon : '🔒'}
</div>
<h3 style={{ fontSize: '18px', fontWeight: 800, margin: '0 0 4px 0', color: selectedAchievement.unlocked ? textColor : subColor }}>
{getAchievementName(selectedAchievement)}
</h3>
<div style={{ width: '40px', height: '3px', background: selectedAchievement.unlocked ? brandColor : 'rgba(0,0,0,0.1)', borderRadius: '2px', margin: '12px auto' }} />
<p style={{ fontSize: '14px', color: subColor, margin: '0 0 16px 0', lineHeight: '1.5' }}>
{getAchievementDesc(selectedAchievement)}
</p>
<div style={{
padding: '10px 16px', borderRadius: radius.md,
background: selectedAchievement.unlocked ? `${brandColor}15` : 'rgba(0,0,0,0.03)',
border: `1px solid ${selectedAchievement.unlocked ? brandColor + '40' : 'rgba(0,0,0,0.06)'}`,
marginBottom: '16px',
}}>
{selectedAchievement.unlocked ? (
<>
<div style={{ fontSize: '13px', fontWeight: 600, color: brandColor }}>✅ {labels.unlockedLabel}</div>
{selectedAchievement.unlocked_at && (
<div style={{ fontSize: '12px', color: subColor, marginTop: '4px' }}>{formatDate(selectedAchievement.unlocked_at, language)}</div>
)}
</>
) : (
<div style={{ fontSize: '13px', fontWeight: 600, color: subColor }}>🔒 {labels.lockedLabel}</div>
)}
</div>
<button onClick={() => setSelectedAchievement(null)}
style={{
...glass({
padding: '12px 24px',
borderRadius: radius.md,
}),
color: textColor,
fontSize: '14px',
fontWeight: 600,
cursor: 'pointer',
transition: 'transform 0.2s ease',
width: '100%',
}}
onTouchStart={(e) => { e.currentTarget.style.transform = 'scale(0.95)'; }}
onTouchEnd={(e) => { e.currentTarget.style.transform = 'scale(1)'; }}>
{labels.close}
</button>
</div>
</div>
)}
{/* Заголовок */}
<div style={{ display: 'flex', alignItems: 'center', gap: '16px', marginBottom: '24px', animation: 'fadeInUp 0.3s ease' }}>
<button
onClick={() => navigate('/menu')}
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: '26px', fontWeight: 900, margin: 0, color: textColor }}>
🏆 {t('leaderboard')}
</h1>
<button
onClick={fetchData}
style={{
marginLeft: 'auto',
...glass({
padding: '8px 12px',
borderRadius: radius.md,
}),
color: subColor,
fontSize: '18px',
cursor: 'pointer',
transition: 'transform 0.2s ease',
}}
onTouchStart={(e) => { e.currentTarget.style.transform = 'scale(0.9) rotate(90deg)'; }}
onTouchEnd={(e) => { e.currentTarget.style.transform = 'scale(1) rotate(0deg)'; }}
>
🔄
</button>
</div>
{/* Пустой рейтинг */}
{entries.length === 0 ? (
<div style={{ textAlign: 'center', padding: '60px 20px', color: subColor, animation: 'fadeInUp 0.3s ease 0.2s both' }}>
<div style={{ fontSize: '48px', marginBottom: '16px' }}>🏆</div>
<div style={{ fontSize: '18px', fontWeight: 600, marginBottom: '8px' }}>{t('noPlayers')}</div>
<div style={{ fontSize: '14px' }}>{t('beFirst')}</div>
</div>
) : (
<>
{/* ТОП-3 БИЛБОРД */}
<div style={{
display: 'grid',
gridTemplateColumns: '1fr 1fr 1fr',
gap: '10px',
marginBottom: '20px',
animation: 'fadeInUp 0.3s ease 0.2s both',
}}>
{entries.filter(e => e.rank <= 3).map((entry) => {
const isCurrentUser = entry.telegram_id === currentUserId;
const medal = getMedalEmoji(entry.rank);
return (
<div
key={entry.telegram_id}
style={{
...glass({
borderRadius: radius.lg,
padding: '16px 10px',
textAlign: 'center',
}),
...getTop3RowStyle(entry.rank),
}}
>
<div style={{ fontSize: '32px', marginBottom: '4px' }}>{medal}</div>
<div style={{ fontSize: '13px', fontWeight: 700, color: textColor, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>
{isCurrentUser ? 'You' : truncateName(entry.username, 10)}
</div>
<div style={{ fontSize: '14px', fontWeight: 800, color: entry.rank === 1 ? '#FFD700' : entry.rank === 2 ? '#C0C0C0' : '#CD7F32', marginTop: '4px' }}>
{entry.total_score.toLocaleString()}
</div>
</div>
);
})}
</div>
{/* Таблица остальных */}
<div style={{
...glass({
borderRadius: radius.lg,
overflow: 'hidden',
}),
animation: 'fadeInUp 0.3s ease 0.3s both',
}}>
<div style={{
display: 'grid',
gridTemplateColumns: '40px 1fr 80px',
gap: '6px',
padding: '12px 14px',
fontSize: '12px',
color: '#FFFFFF',
fontWeight: 700,
background: `linear-gradient(135deg, ${brandColor}, #27AE60)`,
alignItems: 'center',
}}>
<span>#</span>
<span>{t('player')}</span>
<span style={{ textAlign: 'right' }}>{t('score')}</span>
</div>
{entries.filter(e => e.rank > 3).map((entry, index) => {
const isCurrentUser = entry.telegram_id === currentUserId;
const displayName = isCurrentUser ? 'You' : truncateName(entry.username, 15);
return (
<div
key={`${entry.telegram_id}-${entry.rank}`}
style={{
display: 'grid',
gridTemplateColumns: '40px 1fr 80px',
gap: '6px',
padding: '12px 14px',
borderBottom: index < entries.filter(e => e.rank > 3).length - 1 ? '1px solid rgba(0,0,0,0.05)' : 'none',
alignItems: 'center',
fontSize: '13px',
animation: `fadeInUp 0.3s ease ${0.3 + index * 0.02}s both`,
transition: 'background 0.2s ease',
...(isCurrentUser ? {
background: `${brandColor}10`,
borderLeft: `3px solid ${brandColor}`,
borderRight: `3px solid ${brandColor}`,
} : {}),
}}
>
<span style={{
fontWeight: 700,
fontSize: '15px',
color: subColor,
textAlign: 'center',
}}>
{entry.rank}
</span>
<div style={{ display: 'flex', alignItems: 'center', gap: '6px', minWidth: 0 }}>
<span style={{
fontWeight: isCurrentUser ? 700 : 500,
color: isCurrentUser ? brandColor : textColor,
whiteSpace: 'nowrap',
overflow: 'hidden',
textOverflow: 'ellipsis',
maxWidth: '100%',
}}>
{displayName}
</span>
{isCurrentUser && (
<span style={{
fontSize: '9px',
padding: '2px 6px',
background: brandColor,
color: '#FFFFFF',
borderRadius: '10px',
fontWeight: 700,
flexShrink: 0,
lineHeight: '1.2',
}}>
YOU
</span>
)}
</div>
<span style={{
textAlign: 'right',
fontWeight: 700,
color: textColor,
fontSize: '14px',
}}>
{entry.total_score.toLocaleString()}
</span>
</div>
);
})}
</div>
{/* Моё место (если не в топ-50) */}
{myRank && myRank.rank > 50 && (
<div style={{
marginTop: '12px',
...glass({
padding: '12px 14px',
borderRadius: radius.md,
display: 'grid',
gridTemplateColumns: '40px 1fr 80px',
gap: '6px',
alignItems: 'center',
fontSize: '13px',
}),
animation: 'fadeInUp 0.3s ease',
}}>
<span style={{ fontWeight: 700, fontSize: '15px', color: brandColor, textAlign: 'center' }}>{myRank.rank}</span>
<div style={{ display: 'flex', alignItems: 'center', gap: '6px', minWidth: 0 }}>
<span style={{ color: brandColor, fontWeight: 700 }}>You</span>
<span style={{ fontSize: '9px', padding: '2px 6px', background: brandColor, color: '#FFFFFF', borderRadius: '10px', fontWeight: 700, flexShrink: 0 }}>YOU</span>
</div>
<span style={{ textAlign: 'right', fontWeight: 700, color: brandColor, fontSize: '14px' }}>{myRank.total_score.toLocaleString()}</span>
</div>
)}
{/* Сворачиваемые достижения */}
{totalCount > 0 && (
<div style={{ marginTop: '20px' }}>
<button
onClick={() => setShowAchievements(!showAchievements)}
style={{
width: '100%',
...glass({
padding: '16px',
borderRadius: radius.lg,
display: 'flex',
alignItems: 'center',
justifyContent: 'space-between',
}),
color: textColor,
fontSize: '15px',
fontWeight: 700,
cursor: 'pointer',
transition: 'all 0.2s ease',
}}
onTouchStart={(e) => { e.currentTarget.style.transform = 'scale(0.98)'; }}
onTouchEnd={(e) => { e.currentTarget.style.transform = 'scale(1)'; }}
>
<span style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
🏅 {labels.achievements}
<span style={{ fontSize: '12px', color: subColor, fontWeight: 400 }}>
{unlockedCount}/{totalCount} {labels.unlocked}
</span>
</span>
<span style={{ fontSize: '14px', color: subColor, transition: 'transform 0.3s ease', transform: showAchievements ? 'rotate(180deg)' : 'rotate(0deg)' }}>
▼
</span>
</button>
<div style={{ width: '100%', height: '4px', background: 'rgba(0,0,0,0.04)', borderRadius: '2px', marginTop: '8px', overflow: 'hidden' }}>
<div style={{ width: `${totalCount > 0 ? (unlockedCount / totalCount * 100) : 0}%`, height: '100%', background: `linear-gradient(90deg, ${brandColor}, #27AE60)`, borderRadius: '2px', transition: 'width 0.5s ease' }} />
</div>
{showAchievements && (
<div style={{
marginTop: '16px',
...glass({
padding: '16px',
borderRadius: radius.lg,
}),
animation: 'achievementsSlideDown 0.4s ease',
overflow: 'hidden',
}}>
{sortedCategories.map((categoryId, catIndex) => {
const catAchievements = groupedAchievements[categoryId];
const catConfig = ACHIEVEMENT_CATEGORIES[categoryId];
const catUnlocked = catAchievements.filter(a => a.unlocked).length;
const catTotal = catAchievements.length;
const catProgressPercent = catTotal > 0 ? (catUnlocked / catTotal * 100) : 0;
return (
<div
key={categoryId}
style={{
marginBottom: catIndex < sortedCategories.length - 1 ? '20px' : '0',
animation: `categoryFadeIn 0.3s ease ${0.1 + catIndex * 0.08}s both`,
}}
>
<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: '8px' }}>
<div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
<span style={{
fontSize: '18px',
width: '32px',
height: '32px',
borderRadius: '8px',
background: catConfig?.bgColor || 'rgba(0,0,0,0.03)',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
}}>
{catConfig?.icon || '🏆'}
</span>
<span style={{ fontSize: '14px', fontWeight: 700, color: textColor }}>
{getCategoryLabel(categoryId)}
</span>
</div>
<span style={{ fontSize: '12px', fontWeight: 600, color: catProgressPercent === 100 ? brandColor : subColor }}>
{catUnlocked}/{catTotal}
</span>
</div>
<div style={{ width: '100%', height: '3px', background: catConfig?.bgColor || 'rgba(0,0,0,0.04)', borderRadius: '2px', marginBottom: '10px', overflow: 'hidden' }}>
<div style={{ width: `${catProgressPercent}%`, height: '100%', background: catConfig?.color || brandColor, borderRadius: '2px', transition: 'width 0.5s ease' }} />
</div>
<div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(140px, 1fr))', gap: '8px' }}>
{catAchievements.map((ach) => (
<div
key={ach.id}
onClick={() => setSelectedAchievement(ach)}
style={{
display: 'flex',
alignItems: 'center',
gap: '8px',
padding: '10px 12px',
borderRadius: radius.md,
background: ach.unlocked
? `${catConfig?.color || brandColor}15`
: 'rgba(0,0,0,0.02)',
border: `1px solid ${ach.unlocked ? (catConfig?.color || brandColor) + '40' : 'rgba(0,0,0,0.06)'}`,
opacity: ach.unlocked ? 1 : 0.45,
transition: 'all 0.2s ease',
cursor: 'pointer',
}}
onTouchStart={(e) => { e.currentTarget.style.transform = 'scale(0.96)'; }}
onTouchEnd={(e) => { e.currentTarget.style.transform = 'scale(1)'; }}
>
<span style={{ fontSize: '22px', flexShrink: 0 }}>
{ach.unlocked ? ach.icon : '🔒'}
</span>
<div style={{ minWidth: 0 }}>
<div style={{
fontSize: '12px',
fontWeight: 600,
color: ach.unlocked ? textColor : subColor,
whiteSpace: 'nowrap',
overflow: 'hidden',
textOverflow: 'ellipsis',
}}>
{getAchievementName(ach)}
</div>
<div style={{
fontSize: '10px',
color: subColor,
whiteSpace: 'nowrap',
overflow: 'hidden',
textOverflow: 'ellipsis',
marginTop: '2px',
}}>
{getAchievementDesc(ach)}
</div>
</div>
</div>
))}
</div>
</div>
);
})}
</div>
)}
</div>
)}
</>
)}
</div>
</div>
);
};
export default LeaderboardPage;
+549
View File
@@ -0,0 +1,549 @@
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<LessonData | null>(null);
const [loading, setLoading] = useState(true);
const [currentQuestionIndex, setCurrentQuestionIndex] = 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 [hintUsed, setHintUsed] = useState<Record<string, boolean>>({});
const [showHint, setShowHint] = useState(false);
const startTimeRef = useRef<number>(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(() => {
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);
}
};
// 🔧 ИСПРАВЛЕНО: handleHintClick теперь сохраняет ответ с hintUsed=true
const handleHintClick = async () => {
if (!currentQuestion || hintUsed[currentQuestion.question.question_id]) return;
setHintUsed(prev => ({ ...prev, [currentQuestion.question.question_id]: true }));
setShowHint(true);
// Сохраняем ответ с подсказкой (правильный ответ, hintUsed=true)
const correctOption = currentQuestion.options.find(o => o.is_correct);
const correctAnswer = correctOption ? correctOption.option_key : '';
// 🔧 ИСПРАВЛЕНО: isFinalAnswer=true, hintUsed=true — система будет знать, что была подсказка
await saveAnswer(currentQuestion.question.question_id, correctAnswer, true, true);
// 🔧 НОВОЕ: также отмечаем ответ как выбранный, чтобы кнопка "Далее" стала активной
setSelectedAnswers(prev => ({ ...prev, [currentQuestion.question.question_id]: correctAnswer }));
};
const handleNext = async () => {
setShowHint(false);
if (currentQuestionIndex < (lesson?.questions.length || 0) - 1) {
setCurrentQuestionIndex(prev => prev + 1);
setTextInputValue('');
startTimeRef.current = Date.now();
} else {
setIsCompleting(true);
if (sessionId) {
try {
await completeLearningSession(sessionId);
} catch (e) {
console.error('Error completing session:', e);
}
}
navigate(`/lessons/topic/${topicId}`);
}
};
const handleBack = () => {
setShowHint(false);
if (currentQuestionIndex > 0) {
setCurrentQuestionIndex(prev => prev - 1);
setTextInputValue('');
startTimeRef.current = Date.now();
}
};
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 (!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;
const isTranslationQuestion = 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 (
<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); }
}
@keyframes modalFadeIn {
0% { opacity: 0; }
100% { opacity: 1; }
}
@keyframes modalSlideUp {
0% { transform: translateY(20px); opacity: 0; }
100% { transform: translateY(0); opacity: 1; }
}
`}</style>
<div style={{ position: 'relative', zIndex: 1, display: 'flex', flexDirection: 'column', flex: 1 }}>
{/* Модалка подсказки */}
{showHint && correctOption && (
<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',
animation: 'modalFadeIn 0.2s ease', padding: '20px',
backdropFilter: 'blur(4px)', WebkitBackdropFilter: 'blur(4px)',
}}
onClick={(e) => { if (e.target === e.currentTarget) setShowHint(false); }}
>
<div style={{
...glass({
borderRadius: radius.lg,
padding: '20px',
width: '100%',
maxWidth: '360px',
boxShadow: '0 24px 60px rgba(31,38,73,0.20), inset 0 1px 0 rgba(255,255,255,0.85)',
}),
animation: 'modalSlideUp 0.3s ease',
}}>
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '12px' }}>
<h3 style={{ margin: 0, fontSize: '16px', fontWeight: 700, color: textColor }}>
💡 {t('hintButton')}
</h3>
<button
onClick={() => setShowHint(false)}
style={{
...glass({ padding: '6px 12px', borderRadius: radius.sm }),
color: textColor, fontSize: '14px', fontWeight: 600, cursor: 'pointer',
}}
>
✕
</button>
</div>
<div style={{ padding: '12px', background: `${brandColor}10`, borderRadius: radius.md, marginBottom: '12px' }}>
<div style={{ fontSize: '13px', color: subColor, marginBottom: '4px' }}>
{t('correctOption')}:
</div>
<div style={{ fontSize: '16px', fontWeight: 700, color: brandColor }}>
{correctOption.text_pl}
</div>
</div>
{correctOption.wrong_because && (
<div style={{ padding: '12px', background: 'rgba(255,215,0,0.1)', borderRadius: radius.md }}>
<div style={{ fontSize: '13px', color: subColor, marginBottom: '4px' }}>
{t('whyLabel')}:
</div>
<div style={{ fontSize: '14px', color: textColor }}>
{correctOption.wrong_because}
</div>
</div>
)}
<button
onClick={() => setShowHint(false)}
style={{
width: '100%', marginTop: '16px', padding: '12px',
borderRadius: radius.md, border: 'none',
background: `linear-gradient(135deg, ${brandColor}, #27AE60)`,
color: '#FFFFFF', fontSize: '14px', fontWeight: 700, cursor: 'pointer',
}}
>
{t('teacherClose')}
</button>
</div>
</div>
)}
{/* Заголовок */}
<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' }}>
{getLocalized(lesson.lesson, 'title')}
</h1>
</div>
{/* Счётчик */}
<div style={{ textAlign: 'center', marginBottom: '16px', color: subColor, fontSize: '13px' }}>
{t('testQuestion')} {currentQuestionIndex + 1} / {lesson.questions.length}
</div>
{/* Объяснение (только на первом вопросе) */}
{currentQuestionIndex === 0 && (
<div style={{
...glass({
padding: '16px',
borderRadius: radius.lg,
marginBottom: '16px',
}),
animation: 'fadeInUp 0.3s ease 0.1s both',
}}>
<p style={{ fontSize: '14px', lineHeight: '1.6', margin: 0, color: textColor, whiteSpace: 'pre-line' }}>
{getLocalized(lesson.lesson, 'explanation')}
</p>
{lesson.examples.length > 0 && (
<div style={{ marginTop: '12px', padding: '12px', background: `${brandColor}10`, borderRadius: radius.md }}>
{lesson.examples.map((example, i) => (
<div key={i} style={{ marginBottom: '6px' }}>
<div style={{ fontSize: '15px', fontWeight: 700, color: brandColor }}>🇵🇱 {example.text_pl}</div>
<div style={{ fontSize: '13px', color: subColor }}>{getLocalized(example, 'text')}</div>
</div>
))}
</div>
)}
</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}
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>
{isTranslationQuestion
? getLocalized(option, 'text')
: option.text_pl}
</span>
</button>
);
})}
</div>
)}
</div>
)}
{/* Кнопка подсказки */}
<div style={{ marginTop: '12px', animation: 'fadeInUp 0.3s ease 0.2s both' }}>
<button
onClick={handleHintClick}
disabled={isHintUsed}
style={{
width: '100%',
padding: '12px',
borderRadius: radius.md,
border: isHintUsed ? '1px solid rgba(0,0,0,0.06)' : `1px solid ${brandColor}30`,
background: isHintUsed ? 'rgba(0,0,0,0.03)' : `${brandColor}10`,
color: isHintUsed ? subColor : brandColor,
fontSize: '13px',
fontWeight: 600,
cursor: isHintUsed ? 'default' : 'pointer',
opacity: isHintUsed ? 0.5 : 1,
transition: 'all 0.2s ease',
}}
>
{isHintUsed ? `🔒 ${t('hintUsed')}` : `💡 ${t('hintButton')}`}
</button>
</div>
{/* Кнопки навигации */}
<div style={{
display: 'flex',
gap: '12px',
marginTop: '20px',
animation: 'fadeInUp 0.3s ease 0.3s both',
}}>
<button
onClick={handleBack}
disabled={currentQuestionIndex === 0 || isCompleting}
style={{
...glass({
padding: '14px 20px',
borderRadius: radius.md,
}),
color: currentQuestionIndex === 0 ? subColor : textColor,
fontSize: '14px',
fontWeight: 600,
cursor: currentQuestionIndex === 0 ? 'default' : 'pointer',
opacity: currentQuestionIndex === 0 ? 0.5 : 1,
transition: 'all 0.2s ease',
}}
>
← {t('back')}
</button>
<button
onClick={handleNext}
disabled={!isCurrentAnswered || isCompleting}
style={{
flex: 1,
padding: '14px 20px',
borderRadius: radius.md,
border: 'none',
background: isCurrentAnswered
? `linear-gradient(135deg, ${brandColor}, #27AE60)`
: '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 LessonViewPage;
+293
View File
@@ -0,0 +1,293 @@
import { useState, useEffect, useCallback } from 'react';
import { useNavigate } from 'react-router-dom';
import { useLanguage } from '../i18n/LanguageContext';
import { fonts, radius } from '../styles/theme';
import { getLearningLevels, getLearningTopics, getLearningProgress } from '../api';
interface LearningLevel {
code: string;
name_pl: string;
name_ru: string;
name_uk: string;
name_en: string;
}
interface LearningTopic {
topic_id: string;
level_code: string;
order_number: number;
name_pl: string;
name_ru: string;
name_uk: string;
name_en: string;
lessons_completed?: number;
test_completed?: boolean;
test_score?: number;
topic_mastery?: number;
}
const LessonsPage: React.FC = () => {
const navigate = useNavigate();
const { language } = useLanguage();
const [levels, setLevels] = useState<LearningLevel[]>([]);
const [selectedLevel, setSelectedLevel] = useState<string | null>(null);
const [topics, setTopics] = useState<LearningTopic[]>([]);
const [loading, setLoading] = useState(true);
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,
});
const getLevelName = (level: LearningLevel): string => {
const map: Record<string, string> = { pl: level.name_pl, ru: level.name_ru, uk: level.name_uk, en: level.name_en };
return map[language] || level.name_en;
};
const getTopicName = (topic: LearningTopic): string => {
const map: Record<string, string> = { pl: topic.name_pl, ru: topic.name_ru, uk: topic.name_uk, en: topic.name_en };
return map[language] || topic.name_en;
};
useEffect(() => {
setLoading(true);
getLearningLevels()
.then((data: any) => {
setLevels(data.levels || []);
})
.catch(() => {})
.finally(() => setLoading(false));
}, []);
const handleLevelSelect = useCallback(async (levelCode: string) => {
setSelectedLevel(levelCode);
setLoading(true);
try {
const progressData = await getLearningProgress();
const topicsData = await getLearningTopics(levelCode);
// Объединяем прогресс с темами
const progressMap: Record<string, any> = {};
if (progressData.progress) {
progressData.progress.forEach((p: any) => {
progressMap[p.topic_id] = p;
});
}
const mergedTopics = (topicsData.topics || []).map((topic: any) => ({
...topic,
lessons_completed: progressMap[topic.topic_id]?.lessons_completed || 0,
test_completed: progressMap[topic.topic_id]?.test_completed || false,
test_score: progressMap[topic.topic_id]?.test_score,
topic_mastery: progressMap[topic.topic_id]?.topic_mastery,
}));
setTopics(mergedTopics);
} catch (e) {
console.error('Error loading topics:', e);
setTopics([]);
} finally {
setLoading(false);
}
}, []);
if (loading) {
return (
<div style={{
minHeight: '100vh',
background: bgColor,
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
color: subColor,
fontFamily: fonts.main,
fontSize: '18px',
}}>
{language === 'pl' ? 'Ładowanie...' : language === 'ru' ? 'Загрузка...' : language === 'uk' ? 'Завантаження...' : 'Loading...'}
</div>
);
}
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 }} />
<div style={{ position: 'fixed', bottom: '-50px', left: '-40px', width: '240px', height: '240px', borderRadius: '50%', background: '#4FA9E8', opacity: 0.14, filter: 'blur(80px)', pointerEvents: 'none', zIndex: 0 }} />
<style>{`
@keyframes fadeInUp {
0% { transform: translateY(10px); opacity: 0; }
100% { transform: translateY(0); opacity: 1; }
}
`}</style>
<div style={{ position: 'relative', zIndex: 1, display: 'flex', flexDirection: 'column', flex: 1 }}>
{/* Заголовок */}
<div style={{
display: 'flex',
alignItems: 'center',
gap: '16px',
marginBottom: '24px',
animation: 'fadeInUp 0.3s ease',
}}>
<button
onClick={() => {
if (selectedLevel) {
setSelectedLevel(null);
} else {
navigate('/menu');
}
}}
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)'; }}
>
← {language === 'pl' ? 'Powrót' : language === 'ru' ? 'Назад' : language === 'uk' ? 'Назад' : 'Back'}
</button>
<h1 style={{ fontSize: '26px', fontWeight: 900, margin: 0, color: textColor }}>
📚 {language === 'pl' ? 'Lekcje' : language === 'ru' ? 'Уроки' : language === 'uk' ? 'Уроки' : 'Lessons'}
</h1>
</div>
{!selectedLevel ? (
/* Выбор уровня */
<div style={{
display: 'flex',
flexDirection: 'column',
gap: '12px',
animation: 'fadeInUp 0.3s ease 0.1s both',
}}>
<p style={{ textAlign: 'center', fontSize: '15px', color: subColor, marginBottom: '8px' }}>
{language === 'pl' ? 'Wybierz poziom' : language === 'ru' ? 'Выберите уровень' : language === 'uk' ? 'Виберіть рівень' : 'Select level'}
</p>
{levels.map((level, index) => (
<button
key={level.code}
onClick={() => handleLevelSelect(level.code)}
style={{
padding: '18px',
borderRadius: radius.lg,
border: 'none',
background: `linear-gradient(135deg, ${brandColor}, #27AE60)`,
color: '#FFFFFF',
fontSize: '18px',
fontWeight: 700,
cursor: 'pointer',
boxShadow: `0 4px 15px ${brandColor}40`,
transition: 'all 0.2s ease',
display: 'flex',
justifyContent: 'space-between',
alignItems: 'center',
animation: `fadeInUp 0.3s ease ${0.1 + index * 0.05}s both`,
}}
onTouchStart={(e) => { e.currentTarget.style.transform = 'scale(0.96)'; }}
onTouchEnd={(e) => { e.currentTarget.style.transform = 'scale(1)'; }}
>
<span style={{ fontSize: '22px', fontWeight: 800 }}>{level.code}</span>
<span style={{ fontSize: '14px', opacity: 0.9 }}>{getLevelName(level)}</span>
</button>
))}
</div>
) : (
/* Список тем */
<div style={{
display: 'flex',
flexDirection: 'column',
gap: '12px',
animation: 'fadeInUp 0.3s ease 0.1s both',
}}>
<p style={{ textAlign: 'center', fontSize: '15px', color: brandColor, fontWeight: 700, marginBottom: '8px' }}>
{selectedLevel}
</p>
{topics.length === 0 ? (
<p style={{ textAlign: 'center', color: subColor }}>
{language === 'pl' ? 'Brak tematów' : language === 'ru' ? 'Нет тем' : language === 'uk' ? 'Немає тем' : 'No topics'}
</p>
) : (
topics.map((topic, index) => {
const isCompleted = topic.test_completed;
const isUnlocked = index === 0 || topics[index - 1]?.test_completed;
return (
<button
key={topic.topic_id}
onClick={() => {
if (isUnlocked) {
navigate(`/lessons/topic/${topic.topic_id}`);
}
}}
disabled={!isUnlocked}
style={{
...glass({
padding: '16px',
borderRadius: radius.lg,
display: 'flex',
alignItems: 'center',
gap: '12px',
}),
opacity: isUnlocked ? 1 : 0.5,
cursor: isUnlocked ? 'pointer' : 'default',
animation: `fadeInUp 0.3s ease ${0.1 + index * 0.05}s both`,
border: isCompleted ? `2px solid ${brandColor}` : '1px solid rgba(255,255,255,0.7)',
}}
onTouchStart={(e) => { if (isUnlocked) e.currentTarget.style.transform = 'scale(0.97)'; }}
onTouchEnd={(e) => { e.currentTarget.style.transform = 'scale(1)'; }}
>
<span style={{ fontSize: '24px', flexShrink: 0 }}>
{isCompleted ? '✅' : isUnlocked ? '📖' : '🔒'}
</span>
<div style={{ flex: 1, textAlign: 'left' }}>
<div style={{ fontSize: '15px', fontWeight: 700, color: textColor }}>
{index + 1}. {getTopicName(topic)}
</div>
{isCompleted && topic.topic_mastery && (
<div style={{ fontSize: '12px', color: brandColor, marginTop: '2px' }}>
{language === 'pl' ? 'Wynik' : language === 'ru' ? 'Результат' : language === 'uk' ? 'Результат' : 'Score'}: {topic.topic_mastery}%
</div>
)}
</div>
{isUnlocked && !isCompleted && (
<span style={{ fontSize: '18px', color: brandColor }}>→</span>
)}
</button>
);
})
)}
</div>
)}
</div>
</div>
);
};
export default LessonsPage;
+863
View File
@@ -0,0 +1,863 @@
import { useState, useEffect, useRef, useCallback } from 'react';
import { useNavigate } from 'react-router-dom';
import { useLanguage } from '../i18n/LanguageContext';
import { fonts, radius } from '../styles/theme';
import { fetchProgress, getLeaderboard, setUserLevel, getUnreadCount, getUserUnreadCount, getIsAdmin, registerUser } from '../api';
import { getUserId } from '../telegram';
import SupportChatModal from '../components/SupportChatModal';
import OnboardingModal from '../components/OnboardingModal';
import HighlightsCarousel from '../components/HighlightsCarousel';
import FeedModal, { type FeedSection } from '../components/FeedModal';
// 🔧 ОБНОВЛЕНО (18.09.2026): единый FeedModal заменил 4 отдельные модалки.
// Тип SlideId теперь — алиас на FeedSection, чтобы не было конфликта типов.
type SlideId = FeedSection;
const MenuPage: React.FC = () => {
const navigate = useNavigate();
const { t, language, setLang } = useLanguage();
const [nextLevel, setNextLevel] = useState(1);
const [totalScore, setTotalScore] = useState(0);
const [rank, setRank] = useState<number | null>(null);
const [pressing, setPressing] = useState<string | null>(null);
const [showLangModal, setShowLangModal] = useState(false);
const [showLevelModal, setShowLevelModal] = useState(false);
const [showGamesModal, setShowGamesModal] = useState(false);
const [showSupportModal, setShowSupportModal] = useState(false);
const [showOnboarding, setShowOnboarding] = useState(false);
const [currentLevel, setCurrentLevel] = useState('A1');
const [isAdmin, setIsAdmin] = useState(() => {
// Начальное значение из localStorage, чтобы не мигало при загрузке
return localStorage.getItem('filwords_is_admin') === '1';
});
const [unreadCount, setUnreadCount] = useState(0);
// 🔧 Активная модалка карусели (единый FeedModal)
const [activeSlideModal, setActiveSlideModal] = useState<SlideId | null>(null);
const touchStartY = useRef(0);
const touchStartX = useRef(0);
const touchMoved = useRef(false);
const SCROLL_THRESHOLD = 8;
const brandColor = '#2ECC71';
const helpColor = '#E74C3C';
// 🔧 ОБНОВЛЕНО: убраны неиспользуемые цвета pronunciation / typing,
// потому что кнопки перенесены в меню учителя.
const palette: Record<string, string> = {
play: brandColor,
bubble: '#4FA9E8',
sentence: '#A970D6',
wordquiz: '#E8933F',
leaderboard: '#E8B93F',
teacher: '#8B5CF6',
support: '#FF6B6B',
dashboard: '#E8B93F',
};
const languages = [
{ code: 'pl', name: 'Polski', flag: '🇵🇱', short: 'PL' },
{ code: 'ru', name: 'Русский', flag: '🇷🇺', short: 'RU' },
{ code: 'uk', name: 'Українська', flag: '🇺🇦', short: 'UA' },
{ code: 'en', name: 'English', flag: '🇬🇧', short: 'EN' },
];
const currentLang = languages.find(l => l.code === language) || languages[0];
const getSupportLabel = (): string => {
const labels: Record<string, string> = {
pl: 'Wsparcie',
ru: 'Поддержка',
uk: 'Підтримка',
en: 'Support',
};
return labels[language] || labels.en;
};
const getDashboardLabel = (): string => {
const labels: Record<string, string> = {
pl: 'Panel',
ru: 'Дашборд',
uk: 'Дашборд',
en: 'Dashboard',
};
return labels[language] || labels.en;
};
const makeButtonHandlers = useCallback((buttonName: string, action: () => void) => ({
onTouchStart: (e: React.TouchEvent) => {
touchStartY.current = e.touches[0].clientY;
touchStartX.current = e.touches[0].clientX;
touchMoved.current = false;
setPressing(buttonName);
},
onTouchMove: (e: React.TouchEvent) => {
const deltaY = Math.abs(e.touches[0].clientY - touchStartY.current);
const deltaX = Math.abs(e.touches[0].clientX - touchStartX.current);
if (deltaY > SCROLL_THRESHOLD || deltaX > SCROLL_THRESHOLD) {
touchMoved.current = true;
setPressing(null);
}
},
onTouchEnd: () => {
setPressing(null);
if (!touchMoved.current) {
action();
}
},
onMouseDown: () => setPressing(buttonName),
onMouseUp: () => { setPressing(null); action(); },
}), []);
useEffect(() => {
const myId = getUserId();
registerUser()
.then((data) => {
if (typeof data.is_admin === 'boolean') {
setIsAdmin(data.is_admin);
localStorage.setItem('filwords_is_admin', data.is_admin ? '1' : '0');
} else {
getIsAdmin()
.then((adminData) => {
setIsAdmin(adminData.is_admin);
localStorage.setItem('filwords_is_admin', adminData.is_admin ? '1' : '0');
})
.catch(() => {});
}
})
.catch(() => {});
fetchProgress()
.then((data) => {
setNextLevel(data.last_completed_level + 1);
setTotalScore(data.total_score || 0);
if (data.current_level) {
setCurrentLevel(data.current_level);
localStorage.setItem('filwords_level', data.current_level);
}
})
.catch(() => {
setNextLevel(1);
setTotalScore(0);
});
getLeaderboard(100)
.then((data) => {
const leaderboard = data.leaderboard || [];
const myEntry = leaderboard.find((entry: any) =>
entry.telegram_id === myId
);
if (myEntry) {
setRank(myEntry.rank);
}
})
.catch(() => {});
const savedLevel = localStorage.getItem('filwords_level');
if (savedLevel) {
setCurrentLevel(savedLevel);
}
const langSaved = localStorage.getItem('filwords_lang');
const onboardingDone = localStorage.getItem('filwords_onboarding_done');
if (langSaved && !onboardingDone) {
setTimeout(() => setShowOnboarding(true), 500);
}
}, []);
const refreshUnreadCount = useCallback(() => {
if (isAdmin) {
getUnreadCount()
.then((data) => setUnreadCount(data.unread_count || 0))
.catch(() => {});
} else {
getUserUnreadCount()
.then((data) => setUnreadCount(data.unread_count || 0))
.catch(() => {});
}
}, [isAdmin]);
useEffect(() => {
refreshUnreadCount();
if (isAdmin) return;
const intervalId = setInterval(() => {
if (!showSupportModal) {
refreshUnreadCount();
}
}, 60000);
return () => clearInterval(intervalId);
}, [isAdmin, showSupportModal, refreshUnreadCount]);
useEffect(() => {
if (isAdmin) return;
const handleVisibilityChange = () => {
if (document.visibilityState === 'visible' && !showSupportModal) {
refreshUnreadCount();
}
};
document.addEventListener('visibilitychange', handleVisibilityChange);
return () => {
document.removeEventListener('visibilitychange', handleVisibilityChange);
};
}, [isAdmin, showSupportModal, refreshUnreadCount]);
const handleLevelSelect = (level: string) => {
setCurrentLevel(level);
localStorage.setItem('filwords_level', level);
setUserLevel(level).catch(() => {});
setShowLevelModal(false);
};
const handleOpenDashboard = () => {
window.dispatchEvent(new Event('open-dashboard'));
};
const handleOnboardingComplete = () => {
localStorage.setItem('filwords_onboarding_done', '1');
};
// 🔧 Обработчик клика по слайду карусели — открывает FeedModal с нужной секцией
const handleSlideClick = (slideId: SlideId) => {
if (window.Telegram?.WebApp?.HapticFeedback) {
window.Telegram.WebApp.HapticFeedback.impactOccurred('light');
}
setActiveSlideModal(slideId);
};
// 🔧 Обработчик клика по кнопке "очки + рейтинг"
const handleScoreClick = () => {
if (window.Telegram?.WebApp?.HapticFeedback) {
window.Telegram.WebApp.HapticFeedback.impactOccurred('light');
}
navigate('/leaderboard');
};
// 🔧 ОБНОВЛЕНО: убраны typingHandlers и pronunciationHandlers —
// эти разделы теперь живут в меню учителя (☰ → Произношение / Печать).
const teacherHandlers = makeButtonHandlers('teacher', () => navigate('/teacher'));
const gamesHandlers = makeButtonHandlers('games', () => setShowGamesModal(true));
const leaderboardHandlers = makeButtonHandlers('leaderboard', () => navigate('/leaderboard'));
const supportHandlers = makeButtonHandlers('support', () => setShowSupportModal(true));
const dashboardHandlers = makeButtonHandlers('dashboard', handleOpenDashboard);
const onboardingHandlers = makeButtonHandlers('onboarding', () => setShowOnboarding(true));
const glass = (extra: React.CSSProperties = {}): React.CSSProperties => ({
background: 'rgba(255,255,255,0.55)',
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,
});
const getButtonStyle = (name: string, isLarge = false): React.CSSProperties => {
const accent = palette[name] || brandColor;
const isPressed = pressing === name;
return {
padding: isLarge ? '22px' : '18px',
borderRadius: radius.lg,
border: isPressed ? `1px solid ${accent}80` : '1px solid rgba(255,255,255,0.7)',
background: isPressed
? `linear-gradient(180deg, ${accent}E6, ${accent}CC)`
: 'rgba(255,255,255,0.55)',
backdropFilter: 'blur(24px) saturate(180%)',
WebkitBackdropFilter: 'blur(24px) saturate(180%)',
color: isPressed ? '#12271C' : '#1A1A2E',
fontSize: isLarge ? '18px' : '16px',
fontWeight: 700,
cursor: 'pointer',
boxShadow: isPressed
? `0 8px 24px ${accent}50, inset 0 1px 0 rgba(255,255,255,0.6)`
: '0 6px 20px rgba(31,38,73,0.08), inset 0 1px 0 rgba(255,255,255,0.85)',
transform: isPressed ? 'scale(0.97)' : 'scale(1)',
transition: 'all 0.2s ease',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
gap: '10px',
};
};
return (
<div style={{
minHeight: '100vh',
background: '#F4F5F7',
color: '#1A1A2E',
fontFamily: fonts.main,
display: 'flex',
flexDirection: 'column',
padding: '24px',
position: 'relative',
overflow: 'hidden',
}}>
<div style={{ position: 'fixed', top: '-120px', left: '-90px', width: '320px', height: '320px', borderRadius: '50%', background: palette.teacher, opacity: 0.25, filter: 'blur(90px)', pointerEvents: 'none', zIndex: 0 }} />
<div style={{ position: 'fixed', top: '100px', right: '-110px', width: '300px', height: '300px', borderRadius: '50%', background: palette.bubble, opacity: 0.26, filter: 'blur(100px)', pointerEvents: 'none', zIndex: 0 }} />
<div style={{ position: 'fixed', bottom: '140px', left: '-80px', width: '280px', height: '280px', borderRadius: '50%', background: palette.sentence, opacity: 0.22, filter: 'blur(95px)', pointerEvents: 'none', zIndex: 0 }} />
<div style={{ position: 'fixed', bottom: '-90px', right: '-40px', width: '260px', height: '260px', borderRadius: '50%', background: palette.wordquiz, opacity: 0.22, filter: 'blur(90px)', pointerEvents: 'none', zIndex: 0 }} />
<style>{`
@keyframes fadeInUp {
0% { transform: translateY(10px); opacity: 0; }
100% { transform: translateY(0); opacity: 1; }
}
@keyframes modalFadeIn {
0% { opacity: 0; }
100% { opacity: 1; }
}
@keyframes modalSlideUp {
0% { transform: translateY(20px); opacity: 0; }
100% { transform: translateY(0); opacity: 1; }
}
@keyframes badgePulse {
0%, 100% { transform: scale(1); }
50% { transform: scale(1.2); }
}
`}</style>
<div style={{ position: 'relative', zIndex: 1, display: 'flex', flexDirection: 'column', flex: 1 }}>
{/* ============ МОДАЛКИ ============ */}
{/* Онбординг */}
<OnboardingModal
isOpen={showOnboarding}
onClose={() => setShowOnboarding(false)}
onComplete={handleOnboardingComplete}
/>
{/* 🔧 ЕДИНЫЙ FeedModal — заменяет 4 старые модалки карусели */}
<FeedModal
isOpen={activeSlideModal !== null}
onClose={() => setActiveSlideModal(null)}
section={activeSlideModal || 'news'}
isAdmin={isAdmin}
/>
{/* Модальное окно выбора языка */}
{showLangModal && (
<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',
animation: 'modalFadeIn 0.2s ease', padding: '20px',
backdropFilter: 'blur(4px)', WebkitBackdropFilter: 'blur(4px)',
}}
onClick={(e) => { if (e.target === e.currentTarget) setShowLangModal(false); }}
>
<div style={{
...glass({
borderRadius: radius.lg,
padding: '20px',
width: '100%',
maxWidth: '340px',
boxShadow: '0 24px 60px rgba(31,38,73,0.20), inset 0 1px 0 rgba(255,255,255,0.85)',
}),
animation: 'modalSlideUp 0.3s ease',
}}>
<h3 style={{
margin: '0 0 16px 0',
fontSize: '18px',
fontWeight: 700,
textAlign: 'center',
color: '#1A1A2E',
}}>
{t('selectLanguage')}
</h3>
<div style={{ display: 'flex', flexDirection: 'column', gap: '10px' }}>
{languages.map((lang) => (
<button
key={lang.code}
onClick={() => { setLang(lang.code); setShowLangModal(false); }}
style={{
padding: '14px 18px',
borderRadius: radius.md,
border: `2px solid ${lang.code === language ? brandColor : 'rgba(0,0,0,0.06)'}`,
background: lang.code === language ? `${brandColor}18` : 'rgba(255,255,255,0.6)',
color: '#1A1A2E',
fontSize: '16px',
fontWeight: 600,
cursor: 'pointer',
display: 'flex',
alignItems: 'center',
gap: '12px',
boxShadow: lang.code === language ? `0 0 0 3px ${brandColor}15` : 'none',
transition: 'all 0.2s ease',
}}
>
<span style={{ fontSize: '24px' }}>{lang.flag}</span>
<span>{lang.name}</span>
{lang.code === language && (
<span style={{ marginLeft: 'auto', color: brandColor, fontWeight: 800 }}>✓</span>
)}
</button>
))}
</div>
</div>
</div>
)}
{/* Модальное окно выбора уровня */}
{showLevelModal && (
<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',
animation: 'modalFadeIn 0.2s ease', padding: '20px',
backdropFilter: 'blur(4px)', WebkitBackdropFilter: 'blur(4px)',
}}
onClick={(e) => { if (e.target === e.currentTarget) setShowLevelModal(false); }}
>
<div style={{
...glass({
borderRadius: radius.lg,
padding: '20px',
width: '100%',
maxWidth: '340px',
boxShadow: '0 24px 60px rgba(31,38,73,0.20), inset 0 1px 0 rgba(255,255,255,0.85)',
}),
animation: 'modalSlideUp 0.3s ease',
}}>
<h3 style={{
margin: '0 0 16px 0',
fontSize: '18px',
fontWeight: 700,
textAlign: 'center',
color: '#1A1A2E',
}}>
{t('selectLevel')}
</h3>
<div style={{ display: 'flex', flexDirection: 'column', gap: '10px' }}>
{[
{ code: 'A1', descKey: 'levelA1Name', available: true },
{ code: 'A2', descKey: 'levelA2Name', available: true },
{ code: 'B1', descKey: 'levelB1Name', available: true },
{ code: 'B2', descKey: 'levelB2Name', available: false },
{ code: 'C1', descKey: 'levelC1Name', available: false },
{ code: 'C2', descKey: 'levelC2Name', available: false },
].map((level) => (
<button
key={level.code}
onClick={() => level.available && handleLevelSelect(level.code)}
disabled={!level.available}
style={{
padding: '14px 18px',
borderRadius: radius.md,
border: `2px solid ${level.code === currentLevel ? brandColor : level.available ? 'rgba(0,0,0,0.06)' : 'rgba(0,0,0,0.03)'}`,
background: level.code === currentLevel ? `${brandColor}18` : level.available ? 'rgba(255,255,255,0.6)' : 'rgba(0,0,0,0.03)',
color: level.available ? '#1A1A2E' : 'rgba(26,26,46,0.35)',
fontSize: '16px',
fontWeight: 600,
cursor: level.available ? 'pointer' : 'default',
display: 'flex',
alignItems: 'center',
gap: '12px',
boxShadow: level.code === currentLevel ? `0 0 0 3px ${brandColor}15` : 'none',
transition: 'all 0.2s ease',
opacity: level.available ? 1 : 0.7,
}}
>
<span style={{ fontSize: '20px', fontWeight: 800, width: '36px' }}>{level.code}</span>
<span style={{ fontSize: '13px', opacity: 0.7 }}>
{level.available ? t(level.descKey) : `${t(level.descKey)} (${t('comingSoon')})`}
</span>
{level.available ? (
level.code === currentLevel && (
<span style={{ marginLeft: 'auto', color: brandColor, fontWeight: 800 }}>✓</span>
)
) : (
<span style={{ marginLeft: 'auto', fontSize: '16px' }}>🔒</span>
)}
</button>
))}
</div>
</div>
</div>
)}
{/* Модальное окно выбора игры */}
{showGamesModal && (
<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',
animation: 'modalFadeIn 0.2s ease', padding: '20px',
backdropFilter: 'blur(4px)', WebkitBackdropFilter: 'blur(4px)',
}}
onClick={(e) => { if (e.target === e.currentTarget) setShowGamesModal(false); }}
>
<div style={{
...glass({
borderRadius: radius.lg,
padding: '20px',
width: '100%',
maxWidth: '340px',
boxShadow: '0 24px 60px rgba(31,38,73,0.20), inset 0 1px 0 rgba(255,255,255,0.85)',
}),
animation: 'modalSlideUp 0.3s ease',
}}>
<h3 style={{
margin: '0 0 16px 0',
fontSize: '18px',
fontWeight: 700,
textAlign: 'center',
color: '#1A1A2E',
}}>
{t('games') || 'Games'}
</h3>
<div style={{ display: 'flex', flexDirection: 'column', gap: '10px' }}>
<button
onClick={() => { setShowGamesModal(false); navigate(`/play/${nextLevel}`); }}
style={{
padding: '16px 18px',
borderRadius: radius.md,
border: '2px solid rgba(0,0,0,0.06)',
background: 'rgba(255,255,255,0.6)',
color: '#1A1A2E',
fontSize: '16px',
fontWeight: 600,
cursor: 'pointer',
display: 'flex',
alignItems: 'center',
gap: '12px',
transition: 'all 0.2s ease',
}}
>
<span style={{ fontSize: '24px' }}>🎮</span>
<span>{t('play')}</span>
</button>
<button
onClick={() => { setShowGamesModal(false); navigate('/bubble'); }}
style={{
padding: '16px 18px',
borderRadius: radius.md,
border: '2px solid rgba(0,0,0,0.06)',
background: 'rgba(255,255,255,0.6)',
color: '#1A1A2E',
fontSize: '16px',
fontWeight: 600,
cursor: 'pointer',
display: 'flex',
alignItems: 'center',
gap: '12px',
transition: 'all 0.2s ease',
}}
>
<span style={{ fontSize: '24px' }}>🫧</span>
<span>{t('bubbleWords') || 'Bubbles'}</span>
</button>
<button
onClick={() => { setShowGamesModal(false); navigate('/sentence'); }}
style={{
padding: '16px 18px',
borderRadius: radius.md,
border: '2px solid rgba(0,0,0,0.06)',
background: 'rgba(255,255,255,0.6)',
color: '#1A1A2E',
fontSize: '16px',
fontWeight: 600,
cursor: 'pointer',
display: 'flex',
alignItems: 'center',
gap: '12px',
transition: 'all 0.2s ease',
}}
>
<span style={{ fontSize: '24px' }}>📝</span>
<span>{t('sentenceBuilder')}</span>
</button>
<button
onClick={() => { setShowGamesModal(false); navigate('/wordquiz'); }}
style={{
padding: '16px 18px',
borderRadius: radius.md,
border: '2px solid rgba(0,0,0,0.06)',
background: 'rgba(255,255,255,0.6)',
color: '#1A1A2E',
fontSize: '16px',
fontWeight: 600,
cursor: 'pointer',
display: 'flex',
alignItems: 'center',
gap: '12px',
transition: 'all 0.2s ease',
}}
>
<span style={{ fontSize: '24px' }}>🎯</span>
<span>{t('wordQuiz') || 'Выбери слово'}</span>
</button>
</div>
</div>
</div>
)}
{/* Модальное окно поддержки */}
{showSupportModal && (
<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',
animation: 'modalFadeIn 0.2s ease', padding: '20px',
backdropFilter: 'blur(4px)', WebkitBackdropFilter: 'blur(4px)',
}}
onClick={(e) => { if (e.target === e.currentTarget) setShowSupportModal(false); }}
>
<SupportChatModal
isOpen={showSupportModal}
onClose={() => {
setShowSupportModal(false);
refreshUnreadCount();
}}
isAdmin={isAdmin}
onUnreadChange={refreshUnreadCount}
/>
</div>
)}
{/* ============ ВЕРХНИЙ УГОЛ ============ */}
<div style={{
display: 'flex',
justifyContent: 'flex-end',
alignItems: 'center',
gap: '8px',
marginBottom: '32px',
animation: 'fadeInUp 0.3s ease',
}}>
{/* ? — Онбординг */}
<button
{...onboardingHandlers}
style={{
...glass({
padding: '10px 14px',
borderRadius: radius.md,
}),
color: helpColor,
fontSize: '16px',
fontWeight: 800,
cursor: 'pointer',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
transition: 'all 0.2s ease',
flexShrink: 0,
}}
title={
language === 'ru' ? 'Как пользоваться приложением' :
language === 'uk' ? 'Як користуватися додатком' :
language === 'pl' ? 'Jak korzystać z aplikacji' :
'How to use the app'
}
>
?
</button>
{/* 💯 Очки + Рейтинг */}
<button
onClick={handleScoreClick}
style={{
...glass({
padding: '10px 14px',
borderRadius: radius.md,
display: 'flex',
alignItems: 'center',
gap: '6px',
}),
color: '#1A1A2E',
fontSize: '14px',
fontWeight: 800,
cursor: 'pointer',
transition: 'all 0.2s ease',
flexShrink: 0,
}}
onTouchStart={(e) => {
e.currentTarget.style.transform = 'scale(0.95)';
}}
onTouchEnd={(e) => {
e.currentTarget.style.transform = 'scale(1)';
}}
>
<span style={{ fontSize: '14px' }}>💯</span>
<span style={{ color: '#1A1A2E' }}>
{totalScore.toLocaleString()}
</span>
{rank !== null && rank <= 50 && (
<span style={{
fontSize: '11px',
fontWeight: 700,
color: '#B8860B',
background: '#E8B93F15',
padding: '2px 6px',
borderRadius: '6px',
marginLeft: '2px',
}}>
#{rank}
</span>
)}
</button>
{/* A1 ▼ — Уровень */}
<button
onClick={() => setShowLevelModal(true)}
style={{
...glass({
padding: '10px 14px',
borderRadius: radius.md,
display: 'flex',
alignItems: 'center',
gap: '6px',
}),
color: '#4B5563',
fontSize: '14px',
fontWeight: 700,
cursor: 'pointer',
transition: 'all 0.2s ease',
flexShrink: 0,
}}
onTouchStart={(e) => {
e.currentTarget.style.transform = 'scale(0.95)';
}}
onTouchEnd={(e) => {
e.currentTarget.style.transform = 'scale(1)';
}}
>
<span style={{ fontSize: '14px', color: brandColor, fontWeight: 800 }}>
{currentLevel}
</span>
<span style={{ fontSize: '10px', opacity: 0.5 }}>▼</span>
</button>
{/* 🇵🇱 PL ▼ — Язык */}
<button
onClick={() => setShowLangModal(true)}
style={{
...glass({
padding: '10px 14px',
borderRadius: radius.md,
display: 'flex',
alignItems: 'center',
gap: '6px',
}),
color: '#4B5563',
fontSize: '14px',
fontWeight: 700,
cursor: 'pointer',
transition: 'all 0.2s ease',
flexShrink: 0,
}}
onTouchStart={(e) => {
e.currentTarget.style.transform = 'scale(0.95)';
}}
onTouchEnd={(e) => {
e.currentTarget.style.transform = 'scale(1)';
}}
>
<span style={{ fontSize: '16px' }}>{currentLang.flag}</span>
<span>{currentLang.short}</span>
<span style={{ fontSize: '10px', opacity: 0.5 }}>▼</span>
</button>
</div>
{/* ============ ЛОГОТИП ============ */}
<div style={{
textAlign: 'center',
marginBottom: '24px',
animation: 'fadeInUp 0.3s ease 0.05s both',
}}>
<h1 style={{
fontSize: '46px',
fontWeight: 900,
margin: 0,
letterSpacing: '-1px',
color: '#1A1A2E',
}}>
Filwords{' '}
<span style={{
color: brandColor,
textShadow: `0 0 20px ${brandColor}40`,
}}>PL</span>
</h1>
<p style={{ color: '#6B7280', fontSize: '16px', marginTop: '8px' }}>
Ucz się polskiego przez grę.
</p>
</div>
{/* ============ КАРУСЕЛЬ ============ */}
<HighlightsCarousel onSlideClick={handleSlideClick} />
{/* ============ КНОПКИ ============ */}
<div style={{
display: 'flex',
flexDirection: 'column',
gap: '12px',
flex: 1,
overflow: 'auto',
WebkitOverflowScrolling: 'touch',
}}>
<button {...teacherHandlers} style={getButtonStyle('teacher', true)}>
<span>🎓</span> {t('teacher')}
</button>
<button {...gamesHandlers} style={getButtonStyle('play')}>
<span>🎮</span> {t('games') || 'Games'}
</button>
<button {...leaderboardHandlers} style={getButtonStyle('leaderboard')}>
🏆 {t('leaderboard')}
</button>
{/* Кнопка Поддержка */}
<button {...supportHandlers} style={{
...getButtonStyle('support'),
position: 'relative',
}}>
<span>📮</span> {getSupportLabel()}
{unreadCount > 0 && (
<span style={{
position: 'absolute',
top: '8px',
right: '10px',
minWidth: '22px',
height: '22px',
borderRadius: '11px',
background: '#E74C3C',
color: '#FFFFFF',
fontSize: '12px',
fontWeight: 800,
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
padding: '0 6px',
animation: 'badgePulse 2s ease infinite',
boxShadow: '0 2px 8px rgba(231,76,60,0.4)',
}}>
{unreadCount > 99 ? '99+' : unreadCount}
</span>
)}
</button>
{/* Кнопка Дашборд — только для админов */}
{isAdmin && (
<button {...dashboardHandlers} style={getButtonStyle('dashboard')}>
<span>📊</span> {getDashboardLabel()}
</button>
)}
</div>
<div style={{ textAlign: 'center', marginTop: '24px', color: '#9CA3AF', fontSize: '12px' }}>
Filwords PL © 2026
</div>
</div>
</div>
);
};
export default MenuPage;
+626
View File
@@ -0,0 +1,626 @@
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 { 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<PracticeQuestion[]>([]);
const [explanations, setExplanations] = useState<PracticeExplanation[]>([]);
const [sessionId, setSessionId] = useState<number | null>(null);
const [loading, setLoading] = useState(true);
const [currentIndex, setCurrentIndex] = useState(0);
const [selectedAnswers, setSelectedAnswers] = useState<Record<string, string>>({});
const [textInputValue, setTextInputValue] = useState('');
const [isCompleting, setIsCompleting] = useState(false);
const [hintUsed, setHintUsed] = useState<Record<string, boolean>>({});
const [showHint, setShowHint] = useState(false);
const [practiceResult, setPracticeResult] = useState<{ total: number; correct_count: number } | null>(null);
const startTimeRef = useRef<number>(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) => {
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);
}
};
// 🔧 ИСПРАВЛЕНО: handleHintClick теперь сохраняет ответ с hintUsed=true
const handleHintClick = async () => {
if (!currentQuestion || hintUsed[currentQuestion.question.question_id]) return;
setHintUsed(prev => ({ ...prev, [currentQuestion.question.question_id]: true }));
setShowHint(true);
const correctOption = currentQuestion.options.find(o => o.is_correct);
const correctAnswer = correctOption ? correctOption.option_key : '';
// 🔧 ИСПРАВЛЕНО: isFinalAnswer=true, hintUsed=true — система будет знать, что была подсказка
await saveAnswer(currentQuestion.question.question_id, correctAnswer, true, true);
// 🔧 НОВОЕ: также отмечаем ответ как выбранный, чтобы кнопка "Далее" стала активной
setSelectedAnswers(prev => ({ ...prev, [currentQuestion.question.question_id]: correctAnswer }));
};
const handleNext = async () => {
setShowHint(false);
if (currentIndex < questions.length - 1) {
setCurrentIndex(prev => prev + 1);
setTextInputValue('');
startTimeRef.current = Date.now();
} else {
setIsCompleting(true);
const currentQ = questions[currentIndex];
const answer = selectedAnswers[currentQ.question.question_id];
if (answer && sessionId) {
const timeTaken = Date.now() - startTimeRef.current;
// 🔧 ИСПРАВЛЕНО: проверяем, была ли подсказка для этого вопроса
const wasHintUsed = !!hintUsed[currentQ.question.question_id];
try {
await saveLearningAnswer(sessionId, currentQ.question.question_id, answer, timeTaken, true, wasHintUsed);
} catch (e) {
console.error('Error saving final answer:', e);
}
}
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 = () => {
setShowHint(false);
if (currentIndex > 0) {
setCurrentIndex(prev => prev - 1);
setTextInputValue('');
startTimeRef.current = Date.now();
}
};
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 (practiceResult) {
const total = practiceResult.total || 0;
const correct = practiceResult.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',
}}>
<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('practiceCompleted')}
</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('practiceCorrectAnswers')}
</div>
</div>
<button
onClick={() => navigate('/menu')}
style={{
marginTop: '20px',
padding: '16px 32px',
borderRadius: radius.lg,
border: 'none',
background: `linear-gradient(135deg, ${brandColor}, #27AE60)`,
color: '#FFFFFF',
fontSize: '16px',
fontWeight: 700,
cursor: 'pointer',
boxShadow: `0 4px 15px ${brandColor}40`,
}}
onTouchStart={(e) => { e.currentTarget.style.transform = 'scale(0.96)'; }}
onTouchEnd={(e) => { e.currentTarget.style.transform = 'scale(1)'; }}
>
{t('backToMenu')}
</button>
</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;
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 (
<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); }
}
@keyframes modalFadeIn {
0% { opacity: 0; }
100% { opacity: 1; }
}
@keyframes modalSlideUp {
0% { transform: translateY(20px); opacity: 0; }
100% { transform: translateY(0); opacity: 1; }
}
`}</style>
<div style={{ position: 'relative', zIndex: 1, display: 'flex', flexDirection: 'column', flex: 1 }}>
{/* Модалка подсказки */}
{showHint && correctOption && (
<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',
animation: 'modalFadeIn 0.2s ease', padding: '20px',
backdropFilter: 'blur(4px)', WebkitBackdropFilter: 'blur(4px)',
}}
onClick={(e) => { if (e.target === e.currentTarget) setShowHint(false); }}
>
<div style={{
...glass({
borderRadius: radius.lg,
padding: '20px',
width: '100%',
maxWidth: '360px',
boxShadow: '0 24px 60px rgba(31,38,73,0.20), inset 0 1px 0 rgba(255,255,255,0.85)',
}),
animation: 'modalSlideUp 0.3s ease',
}}>
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '12px' }}>
<h3 style={{ margin: 0, fontSize: '16px', fontWeight: 700, color: textColor }}>
💡 {t('hintButton')}
</h3>
<button
onClick={() => setShowHint(false)}
style={{
...glass({ padding: '6px 12px', borderRadius: radius.sm }),
color: textColor, fontSize: '14px', fontWeight: 600, cursor: 'pointer',
}}
>
✕
</button>
</div>
<div style={{ padding: '12px', background: `${brandColor}10`, borderRadius: radius.md, marginBottom: '12px' }}>
<div style={{ fontSize: '13px', color: subColor, marginBottom: '4px' }}>
{t('correctOption')}:
</div>
<div style={{ fontSize: '16px', fontWeight: 700, color: brandColor }}>
{correctOption.text_pl}
</div>
</div>
{correctOption.wrong_because && (
<div style={{ padding: '12px', background: 'rgba(255,215,0,0.1)', borderRadius: radius.md }}>
<div style={{ fontSize: '13px', color: subColor, marginBottom: '4px' }}>
{t('whyLabel')}:
</div>
<div style={{ fontSize: '14px', color: textColor }}>
{correctOption.wrong_because}
</div>
</div>
)}
<button
onClick={() => setShowHint(false)}
style={{
width: '100%', marginTop: '16px', padding: '12px',
borderRadius: radius.md, border: 'none',
background: `linear-gradient(135deg, ${brandColor}, #27AE60)`,
color: '#FFFFFF', fontSize: '14px', fontWeight: 700, cursor: 'pointer',
}}
>
{t('teacherClose')}
</button>
</div>
</div>
)}
{/* Заголовок */}
<div style={{
display: 'flex',
alignItems: 'center',
gap: '16px',
marginBottom: '20px',
animation: 'fadeInUp 0.3s ease',
}}>
<button
onClick={() => navigate('/menu')}
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('practiceTitle')}
</h1>
</div>
{/* Счётчик */}
<div style={{ textAlign: 'center', marginBottom: '12px', 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: '16px',
overflow: 'hidden',
}}>
<div style={{
width: `${((currentIndex + 1) / questions.length) * 100}%`,
height: '100%',
background: `linear-gradient(90deg, ${brandColor}, #27AE60)`,
borderRadius: '2px',
transition: 'width 0.3s ease',
}} />
</div>
{/* Объяснение навыка (если есть) */}
{currentExplanation && (
<div style={{
...glass({
padding: '14px',
borderRadius: radius.lg,
marginBottom: '12px',
}),
border: `1px solid ${brandColor}30`,
animation: 'fadeInUp 0.3s ease 0.1s both',
}}>
<div style={{ fontSize: '13px', fontWeight: 700, color: brandColor, marginBottom: '6px' }}>
📖 {currentExplanation.name}
</div>
{currentExplanation.explanation_ru && (
<div style={{ fontSize: '12px', color: subColor, lineHeight: '1.5' }}>
{getLocalized(currentExplanation, 'explanation')}
</div>
)}
</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}
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={{ marginTop: '12px', animation: 'fadeInUp 0.3s ease 0.2s both' }}>
<button
onClick={handleHintClick}
disabled={isHintUsed}
style={{
width: '100%',
padding: '12px',
borderRadius: radius.md,
border: isHintUsed ? '1px solid rgba(0,0,0,0.06)' : `1px solid ${brandColor}30`,
background: isHintUsed ? 'rgba(0,0,0,0.03)' : `${brandColor}10`,
color: isHintUsed ? subColor : brandColor,
fontSize: '13px',
fontWeight: 600,
cursor: isHintUsed ? 'default' : 'pointer',
opacity: isHintUsed ? 0.5 : 1,
transition: 'all 0.2s ease',
}}
>
{isHintUsed ? `🔒 ${t('hintUsed')}` : `💡 ${t('hintButton')}`}
</button>
</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}
disabled={!isCurrentAnswered || isCompleting}
style={{
flex: 1,
padding: '14px 20px',
borderRadius: radius.md,
border: 'none',
background: isCurrentAnswered
? `linear-gradient(135deg, ${brandColor}, #27AE60)`
: '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('loading')
: isLastQuestion
? t('testFinish')
: `${t('next')} →`}
</button>
</div>
</div>
</div>
);
};
export default PracticeViewPage;
+463
View File
@@ -0,0 +1,463 @@
import { useState, useEffect, useCallback, useRef } from 'react';
import { useNavigate } from 'react-router-dom';
import { useLanguage } from '../i18n/LanguageContext';
import { fonts, radius } from '../styles/theme';
import { getNextPronunciationWord, trackPronunciationOpened, getTTS } from '../api';
import RulesModal from '../components/RulesModal';
import { useAchievements } from '../hooks/useAchievements';
interface PronunciationWord {
word_pl: string;
translation: string;
level: string;
}
const levelColors: Record<string, string> = {
A1: '#2ECC71',
A2: '#27AE60',
B1: '#F39C12',
B2: '#E67E22',
C1: '#E74C3C',
C2: '#C0392B',
};
const PronunciationPage: React.FC = () => {
const navigate = useNavigate();
const { t } = useLanguage();
const [currentWord, setCurrentWord] = useState<PronunciationWord | null>(null);
const [loading, setLoading] = useState(true);
const [isPlaying, setIsPlaying] = useState(false);
const [showRules, setShowRules] = useState(false);
const audioRef = useRef<HTMLAudioElement | null>(null);
const isMountedRef = useRef(true);
const rulesShownRef = useRef(false);
const trackedRef = useRef(false);
const { activeAchievement, showAchievement } = useAchievements();
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,
});
const playWord = async (word: string) => {
// Останавливаем предыдущее аудио
if (audioRef.current) {
audioRef.current.pause();
audioRef.current = null;
}
// Останавливаем Web Speech API, если он что-то говорит
if ('speechSynthesis' in window) {
window.speechSynthesis.cancel();
}
setIsPlaying(true);
try {
// Пробуем Edge TTS через бэкенд
const audioBlob = await getTTS(word, 'male');
const audioUrl = URL.createObjectURL(audioBlob);
const audio = new Audio(audioUrl);
audioRef.current = audio;
audio.onended = () => {
if (isMountedRef.current) setIsPlaying(false);
};
audio.onerror = () => {
// Edge TTS не сработал — пробуем Web Speech API
playWebSpeech(word);
};
await audio.play();
} catch (e) {
console.error('Edge TTS error:', e);
// Edge TTS не сработал — пробуем Web Speech API
playWebSpeech(word);
}
};
const playWebSpeech = (word: string) => {
if ('speechSynthesis' in window) {
const utterance = new SpeechSynthesisUtterance(word);
utterance.lang = 'pl-PL';
utterance.onend = () => {
if (isMountedRef.current) setIsPlaying(false);
};
utterance.onerror = () => {
if (isMountedRef.current) setIsPlaying(false);
};
window.speechSynthesis.speak(utterance);
} else {
if (isMountedRef.current) setIsPlaying(false);
}
};
const fetchWord = useCallback(() => {
setLoading(true);
getNextPronunciationWord()
.then((data: any) => {
if (isMountedRef.current) {
setCurrentWord(data);
}
})
.catch(() => {
if (isMountedRef.current) {
navigate('/menu');
}
})
.finally(() => {
if (isMountedRef.current) {
setLoading(false);
}
});
}, [navigate]);
useEffect(() => {
isMountedRef.current = true;
// Автопоказ правил при первом входе
if (!rulesShownRef.current) {
rulesShownRef.current = true;
const rulesSeen = localStorage.getItem('filwords_rules_pronunciation');
if (!rulesSeen) {
setTimeout(() => {
if (isMountedRef.current) {
setShowRules(true);
localStorage.setItem('filwords_rules_pronunciation', '1');
}
}, 500);
}
}
// Трекинг открытия Произношения
if (!trackedRef.current) {
trackedRef.current = true;
trackPronunciationOpened()
.then((data: any) => {
if (data?.new_achievements && data.new_achievements.length > 0) {
data.new_achievements.forEach((ach: any) => {
showAchievement({
id: ach.code,
icon: ach.icon,
name: ach.name,
});
});
}
})
.catch(() => {});
}
fetchWord();
return () => {
isMountedRef.current = false;
if (audioRef.current) {
audioRef.current.pause();
audioRef.current = null;
}
// Останавливаем Web Speech API при уходе со страницы
if ('speechSynthesis' in window) {
window.speechSynthesis.cancel();
}
};
}, [fetchWord, showAchievement]);
const levelColor = currentWord?.level ? levelColors[currentWord.level] || brandColor : brandColor;
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>
);
}
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: levelColor, opacity: 0.18, filter: 'blur(90px)', pointerEvents: 'none', zIndex: 0 }} />
<div style={{ position: 'fixed', bottom: '-50px', left: '-40px', width: '240px', height: '240px', borderRadius: '50%', background: brandColor, opacity: 0.14, filter: 'blur(80px)', pointerEvents: 'none', zIndex: 0 }} />
<style>{`
@keyframes fadeInUp {
0% { transform: translateY(10px); opacity: 0; }
100% { transform: translateY(0); opacity: 1; }
}
@keyframes pulse {
0%, 100% { transform: scale(1); }
50% { transform: scale(1.05); }
}
@keyframes soundWave {
0%, 100% { height: 8px; }
50% { height: 24px; }
}
@keyframes achievementSlideDown {
0% { transform: translateX(-50%) translateY(-80px); opacity: 0; }
100% { transform: translateX(-50%) translateY(0); opacity: 1; }
}
`}</style>
<div style={{ position: 'relative', zIndex: 1, display: 'flex', flexDirection: 'column', flex: 1 }}>
<RulesModal
isOpen={showRules}
onClose={() => setShowRules(false)}
title={t('pronunciationRulesTitle') || '🔊 Pronunciation Rules'}
content={t('pronunciationRulesContent') || 'Rules content loading...'}
/>
{activeAchievement && (
<div style={{
position: 'fixed', top: '16px', left: '50%', transform: 'translateX(-50%)', zIndex: 900,
background: 'linear-gradient(135deg, #FFD700, #FFA500)',
color: '#FFFFFF', padding: '14px 20px', borderRadius: radius.lg,
boxShadow: '0 8px 30px rgba(255, 215, 0, 0.5)',
display: 'flex', alignItems: 'center', gap: '12px',
minWidth: '250px', maxWidth: '90vw', animation: 'achievementSlideDown 0.4s ease',
}}>
<span style={{ fontSize: '28px', flexShrink: 0 }}>{activeAchievement.icon}</span>
<div>
<div style={{ fontSize: '11px', fontWeight: 600, opacity: 0.9, letterSpacing: '1px', textTransform: 'uppercase' }}>
🏆 {t('achievement') || 'Achievement'}
</div>
<div style={{ fontSize: '15px', fontWeight: 800, marginTop: '2px' }}>
{activeAchievement.name}
</div>
</div>
</div>
)}
{/* Верхняя панель */}
<div style={{
display: 'flex',
justifyContent: 'space-between',
alignItems: 'center',
marginBottom: '24px',
animation: 'fadeInUp 0.3s ease',
}}>
<div style={{ display: 'flex', gap: '8px', alignItems: 'center' }}>
<button
onClick={() => navigate('/menu')}
style={{
...glass({
padding: '10px 18px',
borderRadius: radius.md,
}),
color: textColor,
fontSize: '14px',
fontWeight: 600,
cursor: 'pointer',
flexShrink: 0,
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>
<button
onClick={() => setShowRules(true)}
style={{
...glass({
width: '40px',
height: '40px',
borderRadius: radius.md,
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
}),
color: textColor,
fontSize: '18px',
fontWeight: 700,
cursor: 'pointer',
transition: 'transform 0.2s ease',
flexShrink: 0,
}}
onTouchStart={(e) => { e.currentTarget.style.transform = 'scale(0.95)'; }}
onTouchEnd={(e) => { e.currentTarget.style.transform = 'scale(1)'; }}
>
?
</button>
</div>
<div style={{
fontSize: '14px',
fontWeight: 800,
color: levelColor,
background: `${levelColor}15`,
padding: '4px 10px',
borderRadius: radius.sm,
border: `1px solid ${levelColor}40`,
}}>
{currentWord?.level}
</div>
</div>
{/* Заголовок */}
<div style={{
textAlign: 'center',
marginBottom: '32px',
animation: 'fadeInUp 0.3s ease 0.05s both',
}}>
<h1 style={{
fontSize: '28px',
fontWeight: 900,
margin: 0,
color: textColor,
}}>
🔊 {t('pronunciation') || 'Pronunciation'}
</h1>
<p style={{
color: subColor,
fontSize: '14px',
marginTop: '8px',
}}>
{t('tapToListen') || 'Tap the word to listen'}
</p>
</div>
{/* Карточка со словом */}
{currentWord && (
<div style={{
flex: 1,
...glass({
borderRadius: radius.lg,
padding: '32px',
display: 'flex',
flexDirection: 'column',
justifyContent: 'center',
alignItems: 'center',
gap: '20px',
minHeight: '300px',
}),
border: `2px solid ${levelColor}30`,
animation: 'fadeInUp 0.3s ease 0.1s both',
cursor: 'pointer',
}}
onClick={() => playWord(currentWord.word_pl)}
onTouchStart={(e) => { e.currentTarget.style.transform = 'scale(0.98)'; }}
onTouchEnd={(e) => { e.currentTarget.style.transform = 'scale(1)'; }}
>
{/* Иконка динамика */}
<div style={{
width: '80px',
height: '80px',
borderRadius: '50%',
background: `${levelColor}20`,
border: `2px solid ${levelColor}50`,
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
animation: isPlaying ? 'pulse 1s ease infinite' : 'none',
}}>
<span style={{ fontSize: '36px' }}>🔊</span>
</div>
{/* Польское слово */}
<div style={{
fontSize: '36px',
fontWeight: 900,
color: textColor,
textAlign: 'center',
letterSpacing: '1px',
}}>
{currentWord.word_pl}
</div>
{/* Разделитель */}
<div style={{
width: '60px',
height: '2px',
background: `${levelColor}40`,
borderRadius: '1px',
}} />
{/* Перевод */}
<div style={{
fontSize: '18px',
color: subColor,
textAlign: 'center',
fontWeight: 400,
}}>
{currentWord.translation}
</div>
{/* Индикатор воспроизведения */}
{isPlaying && (
<div style={{ display: 'flex', gap: '4px', alignItems: 'flex-end', height: '24px' }}>
{[0, 1, 2, 3, 4].map((i) => (
<div
key={i}
style={{
width: '4px',
height: '8px',
background: levelColor,
borderRadius: '2px',
animation: `soundWave 0.6s ease infinite ${i * 0.1}s`,
}}
/>
))}
</div>
)}
</div>
)}
{/* Кнопка Далее */}
<button
onClick={fetchWord}
style={{
marginTop: '20px',
padding: '16px',
borderRadius: radius.lg,
border: 'none',
background: `linear-gradient(180deg, ${levelColor}E6, ${levelColor}CC)`,
color: '#FFFFFF',
fontSize: '16px',
fontWeight: 700,
cursor: 'pointer',
boxShadow: `0 8px 24px ${levelColor}50`,
transition: 'all 0.2s ease',
}}
onTouchStart={(e) => { e.currentTarget.style.transform = 'scale(0.96)'; }}
onTouchEnd={(e) => { e.currentTarget.style.transform = 'scale(1)'; }}
>
{t('next') || 'Next'} →
</button>
</div>
</div>
);
};
export default PronunciationPage;
+998
View File
@@ -0,0 +1,998 @@
import { useState, useEffect, useCallback, useRef } from 'react';
import { useNavigate } from 'react-router-dom';
import { useLanguage } from '../i18n/LanguageContext';
import { fonts, radius } from '../styles/theme';
import { getNextSentence, checkSentence, getSentenceHint, fetchProgress } from '../api';
import RulesModal from '../components/RulesModal';
import { useAchievements } from '../hooks/useAchievements';
interface SentenceData {
id: number;
sentence_number: number;
theme: string;
words: string[];
correct_words: string[];
translation: string;
difficulty: number;
tier?: string;
}
const tierLabels: Record<string, Record<string, string>> = {
easy: {
pl: 'łatwy',
ru: 'лёгкий',
uk: 'легкий',
en: 'easy',
},
medium: {
pl: 'średni',
ru: 'средний',
uk: 'середній',
en: 'medium',
},
hard: {
pl: 'trudny',
ru: 'сложный',
uk: 'складний',
en: 'hard',
},
};
const tierColors: Record<string, string> = {
easy: '#2ECC71',
medium: '#F39C12',
hard: '#E74C3C',
};
const SentenceBuilderPage: React.FC = () => {
const navigate = useNavigate();
const { t, language } = useLanguage();
const [sentence, setSentence] = useState<SentenceData | null>(null);
const [availableWords, setAvailableWords] = useState<string[]>([]);
const [selectedWords, setSelectedWords] = useState<string[]>([]);
const [loading, setLoading] = useState(true);
const [completed, setCompleted] = useState(false);
const [isCorrect, setIsCorrect] = useState<boolean | null>(null);
const [checking, setChecking] = useState(false);
const [errorMessage, setErrorMessage] = useState<string | null>(null);
const [showRules, setShowRules] = useState(false);
const [hintsUsed, setHintsUsed] = useState(0);
const [showHintModal, setShowHintModal] = useState(false);
const [hintSentence, setHintSentence] = useState<string>('');
const [currentLevel, setCurrentLevel] = useState('A1');
const [totalScore, setTotalScore] = useState(0);
const { activeAchievement, showAchievement, resetAchievements } = useAchievements();
const hintTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const isMountedRef = useRef(true);
const startTimeRef = useRef<number>(0);
const rulesShownRef = useRef(false);
const brandColor = '#2ECC71';
const palette = { sentence: '#A970D6' };
const textColor = '#1A1A2E';
const subColor = '#6B7280';
const bgColor = '#F4F5F7';
const cardBg = 'rgba(255,255,255,0.55)';
const dangerColor = '#E74C3C';
const MAX_HINTS = 3;
const remainingHints = MAX_HINTS - hintsUsed;
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(() => {
isMountedRef.current = true;
// Загружаем уровень из localStorage
const savedLevel = localStorage.getItem('filwords_level');
if (savedLevel) {
setCurrentLevel(savedLevel);
}
// Загружаем общий счёт
fetchProgress()
.then((data: any) => {
if (isMountedRef.current) {
setTotalScore(data.total_score || 0);
}
})
.catch(() => {});
// Автопоказ правил при первом входе
if (!rulesShownRef.current) {
rulesShownRef.current = true;
const rulesSeen = localStorage.getItem('filwords_rules_sentence');
if (!rulesSeen) {
setTimeout(() => {
if (isMountedRef.current) {
setShowRules(true);
localStorage.setItem('filwords_rules_sentence', '1');
}
}, 500);
}
}
return () => {
isMountedRef.current = false;
if (hintTimeoutRef.current) clearTimeout(hintTimeoutRef.current);
};
}, []);
const fetchSentence = useCallback(() => {
setLoading(true);
setCompleted(false);
setIsCorrect(null);
setSelectedWords([]);
setErrorMessage(null);
setShowRules(false);
setHintsUsed(0);
setShowHintModal(false);
setHintSentence('');
resetAchievements();
startTimeRef.current = Date.now();
getNextSentence()
.then((data: any) => {
if (data.completed) {
setCompleted(true);
} else {
setSentence(data);
setAvailableWords(data.words);
}
})
.catch((err: Error) => {
console.error('Error fetching sentence:', err);
setErrorMessage('Failed to load sentence');
})
.finally(() => setLoading(false));
}, [resetAchievements]);
useEffect(() => {
fetchSentence();
}, [fetchSentence]);
const handleWordClick = (word: string, index: number) => {
if (isCorrect !== null) return;
setAvailableWords(prev => prev.filter((_, i) => i !== index));
setSelectedWords(prev => [...prev, word]);
if (window.Telegram?.WebApp?.HapticFeedback) {
window.Telegram.WebApp.HapticFeedback.impactOccurred('light');
}
};
const handleSelectedWordClick = (index: number) => {
if (isCorrect !== null) return;
const word = selectedWords[index];
setSelectedWords(prev => prev.filter((_, i) => i !== index));
setAvailableWords(prev => [...prev, word]);
if (window.Telegram?.WebApp?.HapticFeedback) {
window.Telegram.WebApp.HapticFeedback.impactOccurred('light');
}
};
const handleHint = async () => {
if (!sentence || hintsUsed >= MAX_HINTS) return;
try {
const data: any = await getSentenceHint(sentence.id);
setHintSentence(data.sentence_pl);
setHintsUsed(prev => prev + 1);
setShowHintModal(true);
if (hintTimeoutRef.current) clearTimeout(hintTimeoutRef.current);
hintTimeoutRef.current = setTimeout(() => {
if (isMountedRef.current) {
setShowHintModal(false);
}
}, 2500);
} catch (err) {
console.error('Error getting hint:', err);
}
};
const handleCheck = async () => {
if (!sentence || selectedWords.length === 0) return;
setChecking(true);
setErrorMessage(null);
try {
const completionTime = Math.floor((Date.now() - startTimeRef.current) / 1000);
const data: any = await checkSentence(sentence.id, selectedWords, completionTime);
setIsCorrect(data.correct);
if (data.correct) {
setTotalScore(prev => prev + (data.score || 0));
if (window.Telegram?.WebApp?.HapticFeedback) {
window.Telegram.WebApp.HapticFeedback.impactOccurred('heavy');
}
if (data.new_achievements && data.new_achievements.length > 0) {
data.new_achievements.forEach((ach: any) => {
showAchievement({
id: ach.code,
icon: ach.icon,
name: ach.name,
});
});
}
} else {
if (window.Telegram?.WebApp?.HapticFeedback) {
window.Telegram.WebApp.HapticFeedback.impactOccurred('medium');
}
setTimeout(() => {
if (isMountedRef.current) {
setAvailableWords(sentence.words);
setSelectedWords([]);
setIsCorrect(null);
}
}, 1500);
}
} catch (err: any) {
console.error('Error checking sentence:', err);
setErrorMessage(err.message || 'Error checking sentence');
setIsCorrect(null);
} finally {
setChecking(false);
}
};
const handleReset = () => {
if (!sentence) return;
setAvailableWords(sentence.words);
setSelectedWords([]);
setIsCorrect(null);
setErrorMessage(null);
};
const getTierLabel = (tier: string): string => {
return tierLabels[tier]?.[language] || tier;
};
const getHintButtonLabel = (): string => {
const labels: Record<string, string> = {
pl: 'Pokaż zdanie',
ru: 'Показать предложение',
uk: 'Показати речення',
en: 'Show sentence',
};
return labels[language] || labels.en;
};
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 (completed) {
return (
<div style={{
minHeight: '100vh',
background: bgColor,
color: textColor,
fontFamily: fonts.main,
display: 'flex',
flexDirection: 'column',
alignItems: 'center',
justifyContent: 'center',
padding: '24px',
}}>
<div style={{ fontSize: '64px', marginBottom: '16px' }}>🎉</div>
<h1 style={{
fontSize: '24px',
fontWeight: 700,
marginBottom: '12px',
textAlign: 'center',
lineHeight: '1.4',
}}>
{t('allSentencesCompleted')}
</h1>
<p style={{
fontSize: '14px',
color: subColor,
marginBottom: '24px',
textAlign: 'center',
}}>
Great job! You've completed all available sentences.
</p>
<button
onClick={() => navigate('/menu')}
style={{
...glass({
padding: '16px 32px',
borderRadius: radius.lg,
}),
color: textColor,
fontSize: '16px',
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>
</div>
);
}
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',
left: '-60px',
width: '260px',
height: '260px',
borderRadius: '50%',
background: palette.sentence,
opacity: 0.22,
filter: 'blur(90px)',
pointerEvents: 'none',
zIndex: 0,
}} />
<div style={{
position: 'fixed',
bottom: '-50px',
right: '-40px',
width: '240px',
height: '240px',
borderRadius: '50%',
background: brandColor,
opacity: 0.16,
filter: 'blur(80px)',
pointerEvents: 'none',
zIndex: 0,
}} />
<style>{`
@keyframes fadeInUp {
0% { transform: translateY(10px); opacity: 0; }
100% { transform: translateY(0); opacity: 1; }
}
@keyframes wordPopIn {
0% { transform: scale(0.8); opacity: 0; }
100% { transform: scale(1); opacity: 1; }
}
@keyframes shake {
0%, 100% { transform: translateX(0); }
25% { transform: translateX(-5px); }
75% { transform: translateX(5px); }
}
@keyframes achievementSlideDown {
0% { transform: translateX(-50%) translateY(-80px); opacity: 0; }
100% { transform: translateX(-50%) translateY(0); opacity: 1; }
}
@keyframes hintModalFadeInOut {
0% { opacity: 0; transform: translateY(-10px); }
10% { opacity: 1; transform: translateY(0); }
90% { opacity: 1; transform: translateY(0); }
100% { opacity: 0; transform: translateY(-10px); }
}
@keyframes hintDotActive {
0%, 100% { transform: scale(1); opacity: 1; }
50% { transform: scale(1.5); opacity: 0.6; }
}
@keyframes hintDotUsed {
0% { transform: scale(1); opacity: 1; }
100% { transform: scale(0); opacity: 0; }
}
`}</style>
<div style={{ position: 'relative', zIndex: 1, display: 'flex', flexDirection: 'column', flex: 1 }}>
<RulesModal
isOpen={showRules}
onClose={() => setShowRules(false)}
title={t('sentenceRulesTitle') || '📝 Sentence Builder Rules'}
content={t('sentenceRulesContent') || 'Rules content loading...'}
/>
{showHintModal && (
<div
style={{
position: 'fixed', top: 0, left: 0, right: 0, bottom: 0,
background: 'rgba(20,22,35,0.15)',
zIndex: 500,
display: 'flex',
alignItems: 'flex-start',
justifyContent: 'center',
paddingTop: '25%',
animation: 'hintModalFadeInOut 2.5s ease forwards',
pointerEvents: 'none',
}}
>
<div style={{
...glass({
padding: '20px 28px',
borderRadius: radius.lg,
}),
border: `2px solid ${brandColor}50`,
boxShadow: `0 12px 40px rgba(31,38,73,0.15), 0 0 24px ${brandColor}25, inset 0 1px 0 rgba(255,255,255,0.85)`,
textAlign: 'center',
maxWidth: '90vw',
}}>
<div style={{ fontSize: '12px', color: brandColor, fontWeight: 700, marginBottom: '10px', letterSpacing: '0.5px', textTransform: 'uppercase' }}>
💡 {getHintButtonLabel()}
</div>
<div style={{
fontSize: '17px',
fontWeight: 700,
color: textColor,
letterSpacing: '0.3px',
lineHeight: '1.5',
}}>
{hintSentence}
</div>
</div>
</div>
)}
{activeAchievement && (
<div style={{
position: 'fixed',
top: '16px',
left: '50%',
transform: 'translateX(-50%)',
zIndex: 900,
background: 'linear-gradient(135deg, #FFD700, #FFA500)',
color: '#FFFFFF',
padding: '14px 20px',
borderRadius: radius.lg,
boxShadow: '0 8px 30px rgba(255, 215, 0, 0.5)',
display: 'flex',
alignItems: 'center',
gap: '12px',
minWidth: '250px',
maxWidth: '90vw',
animation: 'achievementSlideDown 0.4s ease',
}}>
<span style={{ fontSize: '28px', flexShrink: 0 }}>{activeAchievement.icon}</span>
<div>
<div style={{
fontSize: '11px',
fontWeight: 600,
opacity: 0.9,
letterSpacing: '1px',
textTransform: 'uppercase',
}}>
🏆 {t('achievement') || 'Achievement'}
</div>
<div style={{ fontSize: '15px', fontWeight: 800, marginTop: '2px' }}>
{activeAchievement.name}
</div>
</div>
</div>
)}
<div style={{
display: 'flex',
alignItems: 'center',
justifyContent: 'space-between',
marginBottom: '24px',
animation: 'fadeInUp 0.3s ease',
position: 'relative',
minHeight: '40px',
}}>
<div style={{ display: 'flex', gap: '8px', alignItems: 'center', zIndex: 1 }}>
<button
onClick={() => navigate('/menu')}
style={{
...glass({
padding: '10px 18px',
borderRadius: radius.md,
}),
color: textColor,
fontSize: '14px',
fontWeight: 600,
cursor: 'pointer',
transition: 'transform 0.2s ease',
flexShrink: 0,
}}
onTouchStart={(e) => { e.currentTarget.style.transform = 'scale(0.95)'; }}
onTouchEnd={(e) => { e.currentTarget.style.transform = 'scale(1)'; }}
>
← {t('back')}
</button>
<button
onClick={() => setShowRules(true)}
style={{
...glass({
width: '40px',
height: '40px',
borderRadius: radius.md,
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
}),
color: textColor,
fontSize: '18px',
fontWeight: 700,
cursor: 'pointer',
transition: 'transform 0.2s ease',
flexShrink: 0,
}}
onTouchStart={(e) => { e.currentTarget.style.transform = 'scale(0.95)'; }}
onTouchEnd={(e) => { e.currentTarget.style.transform = 'scale(1)'; }}
>
?
</button>
</div>
<div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
<span style={{
fontSize: '12px',
fontWeight: 800,
color: brandColor,
background: `${brandColor}15`,
padding: '4px 8px',
borderRadius: radius.sm,
border: `1px solid ${brandColor}40`,
}}>
{currentLevel}
</span>
{sentence?.tier && (
<div style={{
fontSize: '11px',
fontWeight: 700,
color: '#FFFFFF',
padding: '3px 10px',
borderRadius: radius.sm,
background: tierColors[sentence.tier] || brandColor,
}}>
{getTierLabel(sentence.tier)}
</div>
)}
<div style={{ textAlign: 'right' }}>
<div style={{ fontSize: '10px', color: subColor, marginBottom: '2px' }}>
{t('score')}
</div>
<div style={{ fontSize: '14px', fontWeight: 800, color: brandColor }}>
{totalScore.toLocaleString()}
</div>
</div>
</div>
</div>
<div style={{
...glass({
padding: '20px',
borderRadius: radius.lg,
marginBottom: '20px',
}),
animation: 'fadeInUp 0.3s ease 0.05s both',
}}>
<div style={{
fontSize: '14px',
color: subColor,
marginBottom: '8px',
fontWeight: 500,
}}>
{t('buildSentence')}
</div>
{sentence?.translation && (
<div style={{
fontSize: '15px',
color: brandColor,
fontWeight: 600,
padding: '12px',
background: `${brandColor}15`,
borderRadius: radius.md,
border: `1px solid ${brandColor}30`,
lineHeight: '1.5',
}}>
{sentence.translation}
</div>
)}
</div>
{errorMessage && (
<div style={{
position: 'fixed',
top: '20px',
left: '50%',
transform: 'translateX(-50%)',
padding: '12px 24px',
background: dangerColor,
color: '#FFFFFF',
fontSize: '14px',
fontWeight: 600,
borderRadius: radius.md,
boxShadow: '0 4px 12px rgba(224,78,78,0.4)',
zIndex: 100,
animation: 'fadeInUp 0.25s ease',
}}>
❌ {errorMessage}
</div>
)}
{isCorrect === true && (
<div style={{
textAlign: 'center',
padding: '20px',
marginBottom: '16px',
background: `${brandColor}15`,
borderRadius: radius.lg,
border: `2px solid ${brandColor}40`,
animation: 'fadeInUp 0.3s ease',
}}>
<div style={{ fontSize: '32px', marginBottom: '6px' }}>✅</div>
<div style={{ fontSize: '18px', fontWeight: 700, color: brandColor, marginBottom: '8px' }}>
{t('correctAnswer')}
</div>
<div style={{
fontSize: '16px',
color: textColor,
fontWeight: 600,
padding: '8px',
background: cardBg,
borderRadius: radius.md,
display: 'inline-block',
minWidth: '60%',
}}>
{sentence?.correct_words?.join(' ')}
</div>
{sentence?.translation && (
<div style={{
fontSize: '13px',
color: subColor,
marginTop: '8px',
}}>
{sentence.translation}
</div>
)}
</div>
)}
{isCorrect === false && (
<div style={{
textAlign: 'center',
padding: '16px',
marginBottom: '16px',
background: `${dangerColor}10`,
borderRadius: radius.lg,
border: `2px solid ${dangerColor}40`,
animation: 'shake 0.5s ease',
}}>
<div style={{ fontSize: '18px', fontWeight: 700, color: dangerColor }}>
❌ {t('tryAgain')}
</div>
<div style={{ fontSize: '13px', color: subColor, marginTop: '4px' }}>
Words will reset in a moment...
</div>
</div>
)}
<div style={{
minHeight: '56px',
background: selectedWords.length > 0
? `${palette.sentence}10`
: 'rgba(0,0,0,0.02)',
borderRadius: radius.lg,
padding: '14px',
marginBottom: '20px',
border: `2px dashed ${selectedWords.length > 0 ? palette.sentence + '60' : 'rgba(0,0,0,0.1)'}`,
display: 'flex',
flexWrap: 'wrap',
gap: '8px',
alignItems: 'center',
justifyContent: 'center',
transition: 'all 0.3s ease',
}}>
{selectedWords.length === 0 && (
<span style={{ color: subColor, fontSize: '14px', fontStyle: 'italic' }}>
{t('tapWords')}
</span>
)}
{selectedWords.map((word, index) => (
<button
key={`${word}-${index}`}
onClick={() => handleSelectedWordClick(index)}
disabled={isCorrect !== null}
style={{
padding: '10px 16px',
borderRadius: radius.md,
border: `2px solid ${palette.sentence}`,
background: `${palette.sentence}20`,
color: palette.sentence,
fontSize: '15px',
fontWeight: 700,
cursor: isCorrect !== null ? 'default' : 'pointer',
animation: 'wordPopIn 0.2s ease',
transition: 'all 0.15s ease',
boxShadow: `0 2px 8px ${palette.sentence}30`,
}}
onTouchStart={(e) => {
if (isCorrect === null) {
e.currentTarget.style.transform = 'scale(0.93)';
}
}}
onTouchEnd={(e) => {
if (isCorrect === null) {
e.currentTarget.style.transform = 'scale(1)';
}
}}
>
{word}
</button>
))}
</div>
<div style={{
display: 'flex',
flexWrap: 'wrap',
gap: '10px',
justifyContent: 'center',
marginBottom: '24px',
animation: 'fadeInUp 0.3s ease 0.1s both',
minHeight: '60px',
}}>
{availableWords.map((word, index) => (
<button
key={`${word}-${index}`}
onClick={() => handleWordClick(word, index)}
disabled={isCorrect !== null}
style={{
...glass({
padding: '12px 18px',
borderRadius: radius.md,
}),
color: textColor,
fontSize: '15px',
fontWeight: 600,
cursor: isCorrect !== null ? 'default' : 'pointer',
transition: 'all 0.2s cubic-bezier(0.175, 0.885, 0.32, 1.275)',
}}
onTouchStart={(e) => {
if (isCorrect === null) {
e.currentTarget.style.transform = 'scale(0.93)';
e.currentTarget.style.boxShadow = `0 0 12px ${palette.sentence}40`;
e.currentTarget.style.borderColor = palette.sentence;
}
}}
onTouchEnd={(e) => {
if (isCorrect === null) {
e.currentTarget.style.transform = 'scale(1)';
e.currentTarget.style.boxShadow = '0 6px 20px rgba(31,38,73,0.08)';
e.currentTarget.style.borderColor = 'rgba(255,255,255,0.7)';
}
}}
>
{word}
</button>
))}
</div>
<div style={{
display: 'flex',
gap: '10px',
justifyContent: 'center',
marginBottom: '20px',
animation: 'fadeInUp 0.3s ease 0.15s both',
}}>
<button
onClick={handleHint}
disabled={hintsUsed >= MAX_HINTS}
style={{
flex: 1,
maxWidth: '340px',
padding: '14px 16px',
borderRadius: radius.md,
border: hintsUsed >= MAX_HINTS
? '1px solid rgba(0,0,0,0.06)'
: `1px solid ${brandColor}40`,
background: hintsUsed >= MAX_HINTS
? 'rgba(0,0,0,0.03)'
: `${brandColor}10`,
color: hintsUsed >= MAX_HINTS ? subColor : brandColor,
fontSize: '14px',
fontWeight: 600,
cursor: hintsUsed >= MAX_HINTS ? 'default' : 'pointer',
opacity: hintsUsed >= MAX_HINTS ? 0.6 : 1,
transition: 'all 0.2s ease',
display: 'flex',
flexDirection: 'column',
alignItems: 'center',
gap: '8px',
}}
onTouchStart={(e) => {
if (hintsUsed < MAX_HINTS) e.currentTarget.style.transform = 'scale(0.96)';
}}
onTouchEnd={(e) => {
e.currentTarget.style.transform = 'scale(1)';
}}
>
<span style={{ display: 'flex', alignItems: 'center', gap: '6px' }}>
<span>{hintsUsed >= MAX_HINTS ? '🔒' : '💡'}</span>
<span>{getHintButtonLabel()}</span>
</span>
<div style={{
display: 'flex',
gap: '6px',
justifyContent: 'center',
alignItems: 'center',
height: '12px',
}}>
{Array.from({ length: MAX_HINTS }, (_, i) => {
const isActive = i < remainingHints;
return (
<div
key={i}
style={{
width: '10px',
height: '10px',
borderRadius: '50%',
background: isActive
? `radial-gradient(circle at 30% 30%, ${brandColor}, #1a7a3a)`
: 'rgba(0,0,0,0.1)',
border: isActive
? `1px solid ${brandColor}`
: '1px solid rgba(0,0,0,0.08)',
boxShadow: isActive
? `0 0 6px ${brandColor}80, inset 0 1px 0 rgba(255,255,255,0.5)`
: 'inset 0 1px 2px rgba(0,0,0,0.1)',
animation: isActive
? 'hintDotActive 2s ease infinite'
: hintsUsed >= MAX_HINTS
? 'hintDotUsed 0.4s ease forwards'
: 'none',
transition: 'all 0.3s ease',
}}
/>
);
})}
</div>
<div style={{
fontSize: '10px',
color: hintsUsed >= MAX_HINTS ? dangerColor : subColor,
fontWeight: 500,
}}>
{hintsUsed >= MAX_HINTS
? (t('sentenceHintUsed') || 'Hint used')
: `${remainingHints} ${t('remaining') || 'left'}`}
</div>
</button>
</div>
<div style={{
display: 'flex',
gap: '12px',
justifyContent: 'center',
marginTop: 'auto',
paddingBottom: '20px',
animation: 'fadeInUp 0.3s ease 0.15s both',
}}>
{isCorrect === true ? (
<button
onClick={fetchSentence}
style={{
padding: '16px 32px',
borderRadius: radius.lg,
border: 'none',
background: `linear-gradient(180deg, ${brandColor}E6, ${brandColor}CC)`,
color: '#12271C',
fontSize: '16px',
fontWeight: 700,
cursor: 'pointer',
boxShadow: `0 8px 24px ${brandColor}50`,
transition: 'transform 0.2s ease',
}}
onTouchStart={(e) => {
e.currentTarget.style.transform = 'scale(0.95)';
}}
onTouchEnd={(e) => {
e.currentTarget.style.transform = 'scale(1)';
}}
>
{t('nextLevel')} →
</button>
) : (
<>
<button
onClick={handleReset}
disabled={selectedWords.length === 0}
style={{
...glass({
padding: '16px 24px',
borderRadius: radius.lg,
}),
color: selectedWords.length > 0 ? textColor : subColor,
fontSize: '14px',
fontWeight: 600,
cursor: selectedWords.length === 0 ? 'default' : 'pointer',
opacity: selectedWords.length === 0 ? 0.5 : 1,
transition: 'all 0.2s ease',
}}
onTouchStart={(e) => {
if (selectedWords.length > 0) {
e.currentTarget.style.transform = 'scale(0.95)';
}
}}
onTouchEnd={(e) => {
e.currentTarget.style.transform = 'scale(1)';
}}
>
↩ {t('reset')}
</button>
<button
onClick={handleCheck}
disabled={selectedWords.length === 0 || checking}
style={{
padding: '16px 32px',
borderRadius: radius.lg,
border: 'none',
background: selectedWords.length > 0
? `linear-gradient(180deg, ${palette.sentence}E6, ${palette.sentence}CC)`
: 'rgba(0,0,0,0.1)',
color: selectedWords.length > 0 ? '#FFFFFF' : subColor,
fontSize: '16px',
fontWeight: 700,
cursor: selectedWords.length === 0 ? 'default' : 'pointer',
boxShadow: selectedWords.length > 0 ? `0 8px 24px ${palette.sentence}50` : 'none',
opacity: selectedWords.length === 0 || checking ? 0.6 : 1,
transition: 'all 0.2s ease',
}}
onTouchStart={(e) => {
if (selectedWords.length > 0 && !checking) {
e.currentTarget.style.transform = 'scale(0.95)';
}
}}
onTouchEnd={(e) => {
e.currentTarget.style.transform = 'scale(1)';
}}
>
{checking ? '...' : '✓ ' + t('check')}
</button>
</>
)}
</div>
</div>
</div>
);
};
export default SentenceBuilderPage;
File diff suppressed because it is too large Load Diff
+742
View File
@@ -0,0 +1,742 @@
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 { 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);
const audioRef = useRef<HTMLAudioElement | 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,
});
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]);
const saveAnswer = async (questionId: string, answer: string) => {
const timeTaken = Date.now() - startTimeRef.current;
startTimeRef.current = Date.now();
if (sessionId) {
try {
await saveLearningAnswer(sessionId, questionId, answer, timeTaken, true);
} catch (e) {
console.error('Error saving answer:', e);
}
}
};
const handleAnswerSelect = async (questionId: string, optionKey: string) => {
setSelectedAnswers(prev => ({ ...prev, [questionId]: optionKey }));
await saveAnswer(questionId, optionKey);
};
const handleTextInputChange = async (questionId: string, value: string) => {
setTextInputValue(value);
setSelectedAnswers(prev => ({ ...prev, [questionId]: value }));
};
const handleTextInputBlur = async (questionId: string) => {
if (textInputValue.trim()) {
await saveAnswer(questionId, textInputValue.trim());
}
};
const handleNext = async () => {
if (currentIndex < questions.length - 1) {
setCurrentIndex(prev => prev + 1);
setTextInputValue('');
startTimeRef.current = Date.now();
} else {
setIsCompleting(true);
// Сохраняем ответ последнего вопроса
const currentQ = questions[currentIndex];
const answer = selectedAnswers[currentQ.question.question_id];
if (answer && sessionId) {
const timeTaken = Date.now() - startTimeRef.current;
try {
await saveLearningAnswer(sessionId, currentQ.question.question_id, answer, timeTaken, true);
} catch (e) {
console.error('Error saving final answer:', e);
}
}
// Небольшая задержка для сохранения
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 = () => {
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;
}
if ('speechSynthesis' in window) {
window.speechSynthesis.cancel();
}
setIsPlayingExamples(true);
try {
const audioBlob = await getTTS(polishText, 'male');
const audioUrl = URL.createObjectURL(audioBlob);
const audio = new Audio(audioUrl);
audioRef.current = audio;
audio.onended = () => setIsPlayingExamples(false);
audio.onerror = () => setIsPlayingExamples(false);
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) {
// Нет слабых тем — показываем сообщение
alert(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 {
alert(data.message || t('testPracticeNoWeak'));
setIsStartingPractice(false);
}
} catch (e) {
console.error('Error starting practice:', e);
alert(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',
}}>
<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={handleLoadExamples}
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={handleStartPractice}
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}
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}
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;
+217
View File
@@ -0,0 +1,217 @@
import { useState, useEffect } 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 { getLearningTopic } from '../api';
interface Lesson {
lesson_id: string;
order_number: number;
skill_tag: string;
title_pl: string;
title_ru: string;
title_uk: string;
title_en: string;
completed?: boolean;
}
interface TopicData {
topic_id: string;
name_pl: string;
name_ru: string;
name_uk: string;
name_en: string;
}
const TopicLessonsPage: React.FC = () => {
const navigate = useNavigate();
const { topicId } = useParams<{ topicId: string }>();
const { t } = useLanguage();
const getLocalized = useLocalized();
const [topic, setTopic] = useState<TopicData | null>(null);
const [lessons, setLessons] = useState<Lesson[]>([]);
const [loading, setLoading] = useState(true);
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 (topicId) {
setLoading(true);
getLearningTopic(topicId)
.then((data: any) => {
setTopic(data.topic);
setLessons(data.lessons || []);
})
.catch(() => {})
.finally(() => setLoading(false));
}
}, [topicId]);
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>
);
}
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 }} />
<div style={{ position: 'fixed', bottom: '-50px', left: '-40px', width: '240px', height: '240px', borderRadius: '50%', background: '#A970D6', opacity: 0.14, filter: 'blur(80px)', pointerEvents: 'none', zIndex: 0 }} />
<style>{`
@keyframes fadeInUp {
0% { transform: translateY(10px); opacity: 0; }
100% { transform: translateY(0); opacity: 1; }
}
`}</style>
<div style={{ position: 'relative', zIndex: 1, display: 'flex', flexDirection: 'column', flex: 1 }}>
{/* Заголовок */}
<div style={{
display: 'flex',
alignItems: 'center',
gap: '16px',
marginBottom: '24px',
animation: 'fadeInUp 0.3s ease',
}}>
<button
onClick={() => navigate('/lessons')}
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: '22px', fontWeight: 900, margin: 0, color: textColor }}>
{topic ? getLocalized(topic, 'name') : ''}
</h1>
</div>
{/* Список уроков */}
<div style={{
display: 'flex',
flexDirection: 'column',
gap: '10px',
animation: 'fadeInUp 0.3s ease 0.1s both',
}}>
{lessons.map((lesson, index) => {
const isUnlocked = index === 0 || lessons[index - 1]?.completed;
return (
<button
key={lesson.lesson_id}
onClick={() => {
if (isUnlocked) {
navigate(`/lessons/topic/${topicId}/lesson/${lesson.lesson_id}`);
}
}}
disabled={!isUnlocked}
style={{
...glass({
padding: '14px 16px',
borderRadius: radius.lg,
display: 'flex',
alignItems: 'center',
gap: '12px',
}),
opacity: isUnlocked ? 1 : 0.5,
cursor: isUnlocked ? 'pointer' : 'default',
animation: `fadeInUp 0.3s ease ${0.1 + index * 0.04}s both`,
}}
onTouchStart={(e) => { if (isUnlocked) e.currentTarget.style.transform = 'scale(0.97)'; }}
onTouchEnd={(e) => { e.currentTarget.style.transform = 'scale(1)'; }}
>
<span style={{ fontSize: '20px', flexShrink: 0 }}>
{lesson.completed ? '✅' : isUnlocked ? '📝' : '🔒'}
</span>
<div style={{ flex: 1, textAlign: 'left' }}>
<div style={{ fontSize: '14px', fontWeight: 700, color: textColor }}>
{t('topicLesson')} {index + 1}
</div>
<div style={{ fontSize: '13px', color: subColor, marginTop: '2px' }}>
{getLocalized(lesson, 'title')}
</div>
</div>
{isUnlocked && !lesson.completed && (
<span style={{ fontSize: '18px', color: brandColor }}>→</span>
)}
</button>
);
})}
</div>
{/* Кнопка финального теста */}
<div style={{ marginTop: '20px', animation: 'fadeInUp 0.3s ease 0.5s both' }}>
<button
onClick={() => navigate(`/lessons/test/${topicId}`)}
style={{
width: '100%',
padding: '16px',
borderRadius: radius.lg,
border: 'none',
background: `linear-gradient(135deg, #A970D6, #8B5CF6)`,
color: '#FFFFFF',
fontSize: '16px',
fontWeight: 700,
cursor: 'pointer',
boxShadow: '0 4px 15px rgba(169,112,214,0.4)',
transition: 'all 0.2s ease',
}}
onTouchStart={(e) => { e.currentTarget.style.transform = 'scale(0.96)'; }}
onTouchEnd={(e) => { e.currentTarget.style.transform = 'scale(1)'; }}
>
🎓 {t('topicFinalTest')}
</button>
</div>
</div>
</div>
);
};
export default TopicLessonsPage;
+494
View File
@@ -0,0 +1,494 @@
import { useState, useEffect, useCallback, useRef } from 'react';
import { useNavigate } from 'react-router-dom';
import { useLanguage } from '../i18n/LanguageContext';
import { fonts, radius } from '../styles/theme';
import { getNextTypingSentence, checkTypingSentence, getTypingHint, getTypingProgress, getTTS } from '../api';
interface TypingSentence {
completed: boolean;
sentence_id: number;
translation: string;
level: string;
}
const TypingPage: React.FC = () => {
const navigate = useNavigate();
const { t } = useLanguage();
const [sentence, setSentence] = useState<TypingSentence | null>(null);
const [inputValue, setInputValue] = useState('');
const [loading, setLoading] = useState(true);
const [isCorrect, setIsCorrect] = useState<boolean | null>(null);
const [showAnswer, setShowAnswer] = useState(false);
const [correctAnswer, setCorrectAnswer] = useState('');
const [totalCompleted, setTotalCompleted] = useState(0);
const [totalSentences, setTotalSentences] = useState(0);
const [isPlaying, setIsPlaying] = useState(false);
const audioRef = useRef<HTMLAudioElement | 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,
});
const fetchSentence = useCallback(() => {
setLoading(true);
setIsCorrect(null);
setShowAnswer(false);
setInputValue('');
setCorrectAnswer('');
setIsPlaying(false);
if (audioRef.current) {
audioRef.current.pause();
audioRef.current = null;
}
getNextTypingSentence()
.then((data: any) => {
if (data.completed) {
setSentence({ completed: true, sentence_id: 0, translation: '', level: '' });
} else {
setSentence(data);
}
})
.catch(() => {
navigate('/menu');
})
.finally(() => setLoading(false));
getTypingProgress()
.then((data: any) => {
setTotalCompleted(data.completed || 0);
setTotalSentences(data.total || 0);
})
.catch(() => {});
}, [navigate]);
useEffect(() => {
fetchSentence();
return () => {
if (audioRef.current) {
audioRef.current.pause();
audioRef.current = null;
}
if ('speechSynthesis' in window) {
window.speechSynthesis.cancel();
}
};
}, [fetchSentence]);
const handleCheck = async () => {
if (!sentence || !inputValue.trim()) return;
try {
const data = await checkTypingSentence(sentence.sentence_id, inputValue);
setIsCorrect(data.correct);
setCorrectAnswer(data.correct_answer);
if (data.correct) {
setTotalCompleted(prev => prev + 1);
setTimeout(() => {
fetchSentence();
}, 1500);
}
} catch (e) {
console.error('Error checking sentence:', e);
}
};
const handleShowAnswer = async () => {
if (!sentence) return;
try {
const data = await getTypingHint(sentence.sentence_id);
setCorrectAnswer(data.correct_answer);
setShowAnswer(true);
} catch (e) {
console.error('Error getting hint:', e);
}
};
const playAnswer = async () => {
if (!correctAnswer) return;
if (audioRef.current) {
audioRef.current.pause();
audioRef.current = null;
}
if ('speechSynthesis' in window) {
window.speechSynthesis.cancel();
}
setIsPlaying(true);
try {
const audioBlob = await getTTS(correctAnswer, 'male');
const audioUrl = URL.createObjectURL(audioBlob);
const audio = new Audio(audioUrl);
audioRef.current = audio;
audio.onended = () => setIsPlaying(false);
audio.onerror = () => setIsPlaying(false);
await audio.play();
} catch (e) {
console.error('Error playing TTS:', e);
setIsPlaying(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>
);
}
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 modalFadeIn {
0% { opacity: 0; }
100% { opacity: 1; }
}
@keyframes modalSlideUp {
0% { transform: translateY(20px); opacity: 0; }
100% { transform: translateY(0); opacity: 1; }
}
@keyframes correctPop {
0% { transform: scale(1); }
50% { transform: scale(1.05); }
100% { transform: scale(1); }
}
@keyframes shake {
0%, 100% { transform: translateX(0); }
25% { transform: translateX(-5px); }
75% { transform: translateX(5px); }
}
@keyframes pulse {
0%, 100% { transform: scale(1); }
50% { transform: scale(1.1); }
}
`}</style>
<div style={{ position: 'relative', zIndex: 1, display: 'flex', flexDirection: 'column', flex: 1 }}>
{/* Модалка с ответом */}
{showAnswer && correctAnswer && (
<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',
animation: 'modalFadeIn 0.2s ease', padding: '20px',
backdropFilter: 'blur(4px)', WebkitBackdropFilter: 'blur(4px)',
}}
onClick={(e) => { if (e.target === e.currentTarget) setShowAnswer(false); }}
>
<div style={{
...glass({
borderRadius: radius.lg,
padding: '24px',
width: '100%',
maxWidth: '380px',
textAlign: 'center',
boxShadow: '0 24px 60px rgba(31,38,73,0.20), inset 0 1px 0 rgba(255,255,255,0.85)',
}),
animation: 'modalSlideUp 0.3s ease',
}}>
<div style={{ fontSize: '32px', marginBottom: '12px' }}>🇵🇱</div>
<h3 style={{ margin: '0 0 8px 0', fontSize: '16px', fontWeight: 700, color: subColor }}>
{t('typingShowAnswer')}:
</h3>
<div style={{
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
gap: '10px',
marginBottom: '20px',
flexWrap: 'wrap',
}}>
<div style={{ fontSize: '22px', fontWeight: 800, color: '#1A1A2E' }}>
{correctAnswer}
</div>
<button
onClick={playAnswer}
style={{
width: '40px',
height: '40px',
borderRadius: '50%',
border: `1px solid ${brandColor}40`,
background: isPlaying ? `${brandColor}30` : 'rgba(255,255,255,0.9)',
color: brandColor,
fontSize: '18px',
cursor: 'pointer',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
animation: isPlaying ? 'pulse 0.5s ease infinite' : 'none',
flexShrink: 0,
boxShadow: '0 2px 8px rgba(31,38,73,0.08)',
transition: 'all 0.2s ease',
}}
onTouchStart={(e) => { e.currentTarget.style.transform = 'scale(0.9)'; }}
onTouchEnd={(e) => { e.currentTarget.style.transform = 'scale(1)'; }}
>
🔊
</button>
</div>
<button
onClick={() => setShowAnswer(false)}
style={{
width: '100%',
padding: '14px',
borderRadius: radius.md,
border: 'none',
background: `linear-gradient(135deg, #2ECC71, #27AE60)`,
color: '#FFFFFF',
fontSize: '15px',
fontWeight: 700,
cursor: 'pointer',
}}
>
{t('teacherClose')}
</button>
</div>
</div>
)}
{/* Заголовок */}
<div style={{
display: 'flex',
alignItems: 'center',
gap: '16px',
marginBottom: '20px',
animation: 'fadeInUp 0.3s ease',
}}>
<button
onClick={() => navigate('/menu')}
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: '22px', fontWeight: 900, margin: 0, color: textColor, flex: 1, textAlign: 'center' }}>
⌨️ {t('typingTitle')}
</h1>
</div>
{/* Прогресс */}
<div style={{ textAlign: 'center', marginBottom: '20px', color: subColor, fontSize: '13px' }}>
{t('completed')}: {totalCompleted} / {totalSentences}
</div>
{sentence?.completed ? (
<div style={{ textAlign: 'center', padding: '60px 20px', animation: 'fadeInUp 0.3s ease' }}>
<div style={{ fontSize: '64px', marginBottom: '16px' }}>🎉</div>
<div style={{ fontSize: '18px', fontWeight: 700, color: textColor }}>
{t('allSentencesCompleted')}
</div>
<button
onClick={() => navigate('/menu')}
style={{
marginTop: '20px',
padding: '14px 28px',
borderRadius: radius.lg,
border: 'none',
background: `linear-gradient(135deg, #2ECC71, #27AE60)`,
color: '#FFFFFF',
fontSize: '15px',
fontWeight: 700,
cursor: 'pointer',
}}
>
{t('back')}
</button>
</div>
) : (
<>
{/* Перевод */}
<div style={{
...glass({
padding: '24px',
borderRadius: radius.lg,
marginBottom: '20px',
}),
animation: 'fadeInUp 0.3s ease 0.1s both',
}}>
<div style={{ fontSize: '13px', color: subColor, marginBottom: '8px', fontWeight: 500 }}>
{t('typingInstructions')}
</div>
<div style={{ fontSize: '20px', fontWeight: 700, color: brandColor, lineHeight: '1.4' }}>
{sentence?.translation}
</div>
</div>
{/* Поле ввода */}
<input
type="text"
value={inputValue}
onChange={(e) => setInputValue(e.target.value)}
placeholder={t('typingPlaceholder')}
disabled={isCorrect === true}
style={{
width: '100%',
padding: '16px',
borderRadius: radius.lg,
border: isCorrect === false ? `2px solid #E74C3C` : isCorrect === true ? `2px solid #2ECC71` : '1px solid rgba(255,255,255,0.7)',
background: isCorrect === true ? 'rgba(46,204,113,0.1)' : cardBg,
color: textColor,
fontSize: '18px',
fontWeight: 600,
fontFamily: fonts.main,
outline: 'none',
textAlign: 'center',
transition: 'all 0.2s ease',
boxShadow: isCorrect === false ? '0 0 15px rgba(231,76,60,0.3)' : '0 2px 8px rgba(31,38,73,0.06)',
animation: isCorrect === false ? 'shake 0.4s ease' : 'none',
}}
/>
{/* Статус */}
{isCorrect === true && (
<div style={{
textAlign: 'center',
marginTop: '16px',
padding: '12px',
background: 'rgba(46,204,113,0.1)',
borderRadius: radius.md,
animation: 'correctPop 0.3s ease',
}}>
<span style={{ fontSize: '16px', fontWeight: 700, color: '#2ECC71' }}>
✅ {t('typingCorrect')}
</span>
</div>
)}
{isCorrect === false && (
<div style={{
textAlign: 'center',
marginTop: '16px',
padding: '12px',
background: 'rgba(231,76,60,0.1)',
borderRadius: radius.md,
}}>
<span style={{ fontSize: '16px', fontWeight: 700, color: '#E74C3C' }}>
❌ {t('typingIncorrect')}
</span>
</div>
)}
{/* Кнопки */}
<div style={{ display: 'flex', gap: '10px', marginTop: '20px', animation: 'fadeInUp 0.3s ease 0.2s both' }}>
{isCorrect === true ? (
<button
onClick={fetchSentence}
style={{
flex: 1,
padding: '16px',
borderRadius: radius.lg,
border: 'none',
background: `linear-gradient(135deg, #2ECC71, #27AE60)`,
color: '#FFFFFF',
fontSize: '16px',
fontWeight: 700,
cursor: 'pointer',
}}
>
{t('next')} →
</button>
) : (
<>
<button
onClick={handleShowAnswer}
style={{
flex: 1,
...glass({
padding: '16px',
borderRadius: radius.lg,
}),
color: textColor,
fontSize: '14px',
fontWeight: 600,
cursor: 'pointer',
}}
>
👁️ {t('typingShowAnswer')}
</button>
<button
onClick={handleCheck}
disabled={!inputValue.trim()}
style={{
flex: 1,
padding: '16px',
borderRadius: radius.lg,
border: 'none',
background: inputValue.trim()
? `linear-gradient(135deg, #2ECC71, #27AE60)`
: 'rgba(0,0,0,0.1)',
color: '#FFFFFF',
fontSize: '16px',
fontWeight: 700,
cursor: inputValue.trim() ? 'pointer' : 'default',
opacity: inputValue.trim() ? 1 : 0.5,
}}
>
✓ {t('check')}
</button>
</>
)}
</div>
</>
)}
</div>
</div>
);
};
export default TypingPage;
+580
View File
@@ -0,0 +1,580 @@
import { useState, useEffect, useCallback, useRef } from 'react';
import { useNavigate } from 'react-router-dom';
import { useLanguage } from '../i18n/LanguageContext';
import { fonts, radius } from '../styles/theme';
import { getNextQuiz, checkQuizAnswer, getQuizProgress, fetchProgress } from '../api';
import RulesModal from '../components/RulesModal';
import { useAchievements } from '../hooks/useAchievements';
interface QuizData {
correct_polish: string;
translation: string;
options: string[];
}
const WordQuizPage: React.FC = () => {
const navigate = useNavigate();
const { t, language } = useLanguage();
const [quiz, setQuiz] = useState<QuizData | null>(null);
const [loading, setLoading] = useState(true);
const [totalScore, setTotalScore] = useState(0);
const [wordsGuessed, setWordsGuessed] = useState(0);
const [correctStreak, setCorrectStreak] = useState(0);
const [mistakes, setMistakes] = useState(0);
const [selectedAnswer, setSelectedAnswer] = useState<string | null>(null);
const [isCorrect, setIsCorrect] = useState<boolean | null>(null);
const [isChecking, setIsChecking] = useState(false);
const [errorMessage, setErrorMessage] = useState<string | null>(null);
const [showRules, setShowRules] = useState(false);
const [currentLevel, setCurrentLevel] = useState('A1');
const { activeAchievement, showAchievement } = useAchievements();
const isMountedRef = useRef(true);
const rulesShownRef = useRef(false);
const startTimeRef = useRef<number>(0);
const maxMistakes = 3;
const glass = (extra: React.CSSProperties = {}): React.CSSProperties => ({
background: 'rgba(255,255,255,0.55)',
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,
});
const brandColor = '#2ECC71';
const palette = {
wordquiz: '#E8933F',
};
useEffect(() => {
isMountedRef.current = true;
// Автопоказ правил при первом входе
if (!rulesShownRef.current) {
rulesShownRef.current = true;
const rulesSeen = localStorage.getItem('filwords_rules_wordquiz');
if (!rulesSeen) {
setTimeout(() => {
if (isMountedRef.current) {
setShowRules(true);
localStorage.setItem('filwords_rules_wordquiz', '1');
}
}, 500);
}
}
return () => {
isMountedRef.current = false;
};
}, []);
const fetchQuiz = useCallback(() => {
setLoading(true);
setSelectedAnswer(null);
setIsCorrect(null);
setErrorMessage(null);
setMistakes(0);
startTimeRef.current = Date.now();
getNextQuiz()
.then((data: any) => {
if (isMountedRef.current) {
setQuiz(data);
}
})
.catch((err: Error) => {
console.error('Error fetching quiz:', err);
if (isMountedRef.current) {
setErrorMessage('Failed to load quiz');
}
})
.finally(() => {
if (isMountedRef.current) {
setLoading(false);
}
});
}, []);
useEffect(() => {
fetchQuiz();
fetchProgress()
.then((data: any) => {
if (isMountedRef.current) {
setTotalScore(data.total_score || 0);
if (data.current_level) {
setCurrentLevel(data.current_level);
}
}
})
.catch(() => {});
getQuizProgress()
.then((data: any) => {
if (isMountedRef.current) {
setWordsGuessed(data.words_guessed || 0);
setCorrectStreak(data.correct_streak || 0);
}
})
.catch(() => {});
}, [fetchQuiz]);
const handleAnswer = useCallback(async (answer: string) => {
if (!quiz || isChecking || isCorrect !== null) return;
setSelectedAnswer(answer);
setIsChecking(true);
const completionTime = Math.floor((Date.now() - startTimeRef.current) / 1000);
try {
const data: any = await checkQuizAnswer(quiz.correct_polish, answer, mistakes, completionTime);
if (isMountedRef.current) {
if (data.correct) {
setIsCorrect(true);
setTotalScore(prev => prev + (data.score || 0));
setWordsGuessed(prev => prev + 1);
setCorrectStreak(data.correct_streak || 0);
fetchProgress().catch(() => {});
// Показываем достижения
if (data.new_achievements && data.new_achievements.length > 0) {
data.new_achievements.forEach((ach: any) => {
showAchievement({
id: ach.code,
icon: ach.icon,
name: ach.name,
});
});
}
if (window.Telegram?.WebApp?.HapticFeedback) {
window.Telegram.WebApp.HapticFeedback.impactOccurred('heavy');
}
setTimeout(() => {
if (isMountedRef.current) {
setMistakes(0);
fetchQuiz();
}
}, 1000);
} else {
setIsCorrect(false);
const newMistakes = mistakes + 1;
setMistakes(newMistakes);
setCorrectStreak(0);
startTimeRef.current = Date.now();
if (window.Telegram?.WebApp?.HapticFeedback) {
window.Telegram.WebApp.HapticFeedback.impactOccurred('medium');
}
if (newMistakes >= maxMistakes) {
setTimeout(() => {
if (isMountedRef.current) {
setMistakes(0);
fetchQuiz();
}
}, 1500);
} else {
setTimeout(() => {
if (isMountedRef.current) {
setSelectedAnswer(null);
setIsCorrect(null);
}
}, 800);
}
}
}
} catch (err: any) {
console.error('Error checking answer:', err);
if (isMountedRef.current) {
setErrorMessage(err.message || 'Error checking answer');
}
} finally {
if (isMountedRef.current) {
setIsChecking(false);
}
}
}, [quiz, isChecking, isCorrect, mistakes, fetchQuiz, showAchievement]);
const getOptionStyle = (option: string): React.CSSProperties => {
if (isCorrect === true && option === quiz?.correct_polish) {
return {
background: `linear-gradient(180deg, ${brandColor}E6, ${brandColor}CC)`,
border: `2px solid ${brandColor}`,
color: '#12271C',
fontWeight: 700,
boxShadow: `0 8px 24px ${brandColor}50, inset 0 1px 0 rgba(255,255,255,0.4)`,
};
}
if (isCorrect === false && option === selectedAnswer) {
return {
background: 'linear-gradient(180deg, #E74C3CE6, #E74C3CCC)',
border: '2px solid #E74C3C',
color: '#FFFFFF',
fontWeight: 700,
boxShadow: '0 8px 24px rgba(231,76,60,0.35), inset 0 1px 0 rgba(255,255,255,0.3)',
};
}
if (selectedAnswer === option && isChecking) {
return {
background: `${palette.wordquiz}25`,
border: `2px solid ${palette.wordquiz}`,
color: palette.wordquiz,
fontWeight: 700,
};
}
return {
background: 'rgba(255,255,255,0.55)',
backdropFilter: 'blur(24px) saturate(180%)',
WebkitBackdropFilter: 'blur(24px) saturate(180%)',
border: '1px solid rgba(255,255,255,0.7)',
color: '#1A1A2E',
fontWeight: 700,
boxShadow: '0 6px 20px rgba(31,38,73,0.08), inset 0 1px 0 rgba(255,255,255,0.85)',
};
};
if (loading) {
return (
<div style={{
minHeight: '100vh',
background: '#F4F5F7',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
color: '#6B7280',
fontFamily: fonts.main,
fontSize: '18px',
}}>
{t('loading')}...
</div>
);
}
return (
<div style={{
minHeight: '100vh',
background: '#F4F5F7',
color: '#1A1A2E',
fontFamily: fonts.main,
padding: '24px',
display: 'flex',
flexDirection: 'column',
position: 'relative',
overflow: 'hidden',
}}>
<div style={{ position: 'fixed', top: '-100px', right: '-80px', width: '280px', height: '280px', borderRadius: '50%', background: palette.wordquiz, opacity: 0.28, filter: 'blur(100px)', pointerEvents: 'none', zIndex: 0 }} />
<div style={{ position: 'fixed', bottom: '-60px', left: '-60px', width: '240px', height: '240px', borderRadius: '50%', background: brandColor, opacity: 0.22, filter: 'blur(90px)', pointerEvents: 'none', zIndex: 0 }} />
<style>{`
@keyframes fadeInUp {
0% { transform: translateY(10px); opacity: 0; }
100% { transform: translateY(0); opacity: 1; }
}
@keyframes correctPop {
0% { transform: scale(1); }
50% { transform: scale(1.05); }
100% { transform: scale(1); }
}
@keyframes shake {
0%, 100% { transform: translateX(0); }
25% { transform: translateX(-5px); }
75% { transform: translateX(5px); }
}
@keyframes firePop {
0% { transform: scale(0); opacity: 0; }
60% { transform: scale(1.3); opacity: 1; }
100% { transform: scale(1); opacity: 1; }
}
@keyframes achievementSlideDown {
0% { transform: translateX(-50%) translateY(-80px); opacity: 0; }
100% { transform: translateX(-50%) translateY(0); opacity: 1; }
}
`}</style>
<div style={{ position: 'relative', zIndex: 1, display: 'flex', flexDirection: 'column', flex: 1 }}>
<RulesModal
isOpen={showRules}
onClose={() => setShowRules(false)}
title={t('wordQuizRulesTitle') || '🎯 Word Quiz Rules'}
content={t('wordQuizRulesContent') || 'Rules content loading...'}
/>
{/* Плашка достижения */}
{activeAchievement && (
<div style={{
position: 'fixed', top: '16px', left: '50%', transform: 'translateX(-50%)', zIndex: 900,
background: 'linear-gradient(135deg, #FFD700, #FFA500)',
color: '#FFFFFF', padding: '14px 20px', borderRadius: radius.lg,
boxShadow: '0 8px 30px rgba(255, 215, 0, 0.5)',
display: 'flex', alignItems: 'center', gap: '12px',
minWidth: '250px', maxWidth: '90vw', animation: 'achievementSlideDown 0.4s ease',
}}>
<span style={{ fontSize: '28px', flexShrink: 0 }}>{activeAchievement.icon}</span>
<div>
<div style={{ fontSize: '11px', fontWeight: 600, opacity: 0.9, letterSpacing: '1px', textTransform: 'uppercase' }}>
🏆 {t('achievement') || 'Achievement'}
</div>
<div style={{ fontSize: '15px', fontWeight: 800, marginTop: '2px' }}>
{activeAchievement.name}
</div>
</div>
</div>
)}
<div style={{
display: 'flex',
justifyContent: 'space-between',
alignItems: 'center',
marginBottom: '24px',
animation: 'fadeInUp 0.3s ease',
}}>
<div style={{ display: 'flex', gap: '8px', alignItems: 'center' }}>
<button
onClick={() => navigate('/menu')}
style={{
...glass({
padding: '10px 18px',
borderRadius: radius.md,
}),
color: '#1A1A2E',
fontSize: '14px',
fontWeight: 600,
cursor: 'pointer',
flexShrink: 0,
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>
<button
onClick={() => setShowRules(true)}
style={{
...glass({
width: '40px',
height: '40px',
borderRadius: radius.md,
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
}),
color: '#1A1A2E',
fontSize: '18px',
fontWeight: 700,
cursor: 'pointer',
transition: 'transform 0.2s ease',
flexShrink: 0,
}}
onTouchStart={(e) => { e.currentTarget.style.transform = 'scale(0.95)'; }}
onTouchEnd={(e) => { e.currentTarget.style.transform = 'scale(1)'; }}
>
?
</button>
</div>
<div style={{ textAlign: 'right', display: 'flex', alignItems: 'center', gap: '10px' }}>
<div style={{
fontSize: '14px',
fontWeight: 800,
color: brandColor,
background: `${brandColor}15`,
padding: '4px 10px',
borderRadius: radius.sm,
border: `1px solid ${brandColor}40`,
}}>
{currentLevel}
</div>
<div>
<div style={{ fontSize: '11px', color: '#6B7280', marginBottom: '2px' }}>
{t('score')}
</div>
<div style={{
fontSize: '18px',
fontWeight: 800,
color: brandColor,
}}>
{totalScore}
</div>
</div>
</div>
</div>
{quiz && (
<div style={{
flex: 1,
display: 'flex',
flexDirection: 'column',
gap: '20px',
animation: 'fadeInUp 0.3s ease 0.15s both',
}}>
<div style={{
...glass({
padding: '24px',
borderRadius: radius.lg,
textAlign: 'center',
}),
boxShadow: `0 8px 28px rgba(31,38,73,0.10), 0 0 20px ${brandColor}20, inset 0 1px 0 rgba(255,255,255,0.85)`,
}}>
<div style={{
fontSize: '13px',
color: '#6B7280',
marginBottom: '8px',
fontWeight: 500,
}}>
{t('chooseTranslation') || 'Choose the correct translation:'}
</div>
<div style={{
fontSize: '22px',
fontWeight: 700,
color: brandColor,
padding: '10px',
background: `${brandColor}15`,
borderRadius: radius.md,
}}>
{quiz.translation}
</div>
</div>
<div style={{
display: 'flex',
flexDirection: 'column',
gap: '12px',
}}>
{quiz.options.map((option, index) => (
<button
key={`${option}-${index}`}
onClick={() => handleAnswer(option)}
disabled={isChecking || isCorrect === true}
style={{
padding: '18px',
borderRadius: radius.lg,
fontSize: '17px',
fontWeight: 700,
cursor: isChecking || isCorrect === true ? 'default' : 'pointer',
transition: 'all 0.2s ease',
animation: isCorrect === false && option === selectedAnswer
? 'shake 0.4s ease'
: isCorrect === true && option === quiz.correct_polish
? 'correctPop 0.3s ease'
: 'none',
...getOptionStyle(option),
}}
onTouchStart={(e) => {
if (!isChecking && isCorrect === null) {
e.currentTarget.style.transform = 'scale(0.96)';
}
}}
onTouchEnd={(e) => {
e.currentTarget.style.transform = 'scale(1)';
}}
>
{option}
</button>
))}
</div>
{errorMessage && (
<div style={{
textAlign: 'center',
padding: '12px',
background: 'rgba(231,76,60,0.08)',
borderRadius: radius.md,
color: '#E74C3C',
fontSize: '14px',
fontWeight: 600,
}}>
❌ {errorMessage}
</div>
)}
{mistakes >= maxMistakes && (
<div style={{
textAlign: 'center',
padding: '16px',
background: 'rgba(231,76,60,0.08)',
borderRadius: radius.lg,
border: '2px solid rgba(231,76,60,0.3)',
}}>
<div style={{ fontSize: '16px', fontWeight: 700, color: '#E74C3C' }}>
{t('outOfLives') || 'Out of lives!'}
</div>
<div style={{ fontSize: '13px', color: '#6B7280', marginTop: '4px' }}>
+10 {t('points') || 'points'}
</div>
</div>
)}
{isCorrect === true && (
<div style={{
textAlign: 'center',
padding: '16px',
background: `${brandColor}15`,
borderRadius: radius.lg,
border: `2px solid ${brandColor}40`,
}}>
<div style={{ fontSize: '16px', fontWeight: 700, color: brandColor }}>
✅ {t('correctAnswer')}
</div>
</div>
)}
</div>
)}
<div style={{
...glass({
display: 'flex',
justifyContent: 'center',
gap: '24px',
marginTop: '20px',
padding: '12px 16px',
borderRadius: radius.lg,
}),
animation: 'fadeInUp 0.3s ease 0.2s both',
}}>
<div style={{ textAlign: 'center', minWidth: '60px' }}>
<div style={{ fontSize: '10px', color: '#6B7280', marginBottom: '2px' }}>
{t('wordsGuessed') || 'Угадано'}
</div>
<div style={{ fontSize: '18px', fontWeight: 800, color: palette.wordquiz }}>
{wordsGuessed}
</div>
</div>
<div style={{ textAlign: 'center', minWidth: '60px' }}>
<div style={{ fontSize: '10px', color: '#6B7280', marginBottom: '2px' }}>
{language === 'pl' ? 'Seria' : language === 'ru' ? 'Серия' : language === 'uk' ? 'Серія' : 'Streak'}
</div>
<div style={{
fontSize: '18px',
fontWeight: 800,
color: correctStreak >= 5 ? brandColor : '#1A1A2E',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
gap: '4px',
}}>
{correctStreak >= 5 && (
<span style={{
display: 'inline-block',
animation: 'firePop 0.3s ease',
fontSize: '16px',
}}>🔥</span>
)}
{correctStreak}
</div>
</div>
</div>
</div>
</div>
);
};
export default WordQuizPage;
+764
View File
@@ -0,0 +1,764 @@
import { useState, useEffect, useCallback, useRef } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import { useLanguage } from '../i18n/LanguageContext';
import { fonts, radius } from '../styles/theme';
import { getLevel, completeLevel, fetchProgress } from '../api';
import LetterGrid from '../components/LetterGrid';
import HintPanel from '../components/HintPanel';
import RulesModal from '../components/RulesModal';
import { useAchievements } from '../hooks/useAchievements';
interface LevelData {
id: number;
level_number: number;
grid_size: number;
grid_letters: string[][];
word_paths?: Record<string, [number, number][]>;
}
interface WordItem {
word_pl: string;
translation: string;
}
interface ConfettiPiece {
id: number;
x: number;
y: number;
color: string;
size: number;
rotation: number;
animationDuration: number;
animationDelay: number;
}
const WordSearchPage: React.FC = () => {
const { levelNumber } = useParams<{ levelNumber: string }>();
const navigate = useNavigate();
const { t } = useLanguage();
const [level, setLevel] = useState<LevelData | null>(null);
const [words, setWords] = useState<WordItem[]>([]);
const [foundWords, setFoundWords] = useState<string[]>([]);
const [loading, setLoading] = useState(true);
const [firstLetterHintsUsed, setFirstLetterHintsUsed] = useState(0);
const [showWordModal, setShowWordModal] = useState(false);
const [firstLetterCell, setFirstLetterCell] = useState<[number, number] | null>(null);
const [message, setMessage] = useState<string | null>(null);
const [errorMessage, setErrorMessage] = useState<string | null>(null);
const [completed, setCompleted] = useState(false);
const [isTransitioning, setIsTransitioning] = useState(false);
const [confetti, setConfetti] = useState<ConfettiPiece[]>([]);
const [newFoundWord, setNewFoundWord] = useState<string | null>(null);
const [totalScore, setTotalScore] = useState(0);
const [alreadyCompleted, setAlreadyCompleted] = useState(false);
const [showRules, setShowRules] = useState(false);
const [currentLevel, setCurrentLevel] = useState('A1');
const { activeAchievement, showAchievement, resetAchievements } = useAchievements();
const messageTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const errorTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const foundWordsRef = useRef<string[]>([]);
const completedSentRef = useRef(false);
const firstLetterHintsUsedRef = useRef(0);
const isMountedRef = useRef(true);
const rulesShownRef = useRef(false);
const startTimeRef = useRef<number>(0);
const perfectStreakRef = useRef<number>(0);
const num = parseInt(levelNumber || '1');
const totalLevels = 550;
const maxFirstLetterHints = 3;
const confettiColors = ['#FF6B6B', '#4ECDC4', '#45B7D1', '#96CEB4', '#FFEAA7', '#DDA0DD', '#98D8C8', '#F7DC6F', '#FF8A5C', '#2ECC71'];
const brandColor = '#2ECC71';
const palette = { play: brandColor };
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,
});
const generateConfetti = useCallback(() => {
const pieces: ConfettiPiece[] = [];
for (let i = 0; i < 50; i++) {
pieces.push({
id: i,
x: Math.random() * 100,
y: -10 - Math.random() * 20,
color: confettiColors[Math.floor(Math.random() * confettiColors.length)],
size: Math.random() * 8 + 4,
rotation: Math.random() * 360,
animationDuration: Math.random() * 2 + 2,
animationDelay: Math.random() * 1.5,
});
}
return pieces;
}, []);
const checkWordMatch = useCallback((cells: [number, number][]): string | null => {
if (!level?.word_paths) return null;
const cellsStr = cells.map(([r, c]) => `${r},${c}`).join('|');
for (const [word, path] of Object.entries(level.word_paths)) {
if (foundWordsRef.current.includes(word)) continue;
const pathStr = path.map(([r, c]) => `${r},${c}`).join('|');
if (cellsStr === pathStr || cellsStr === path.slice().reverse().map(([r, c]) => `${r},${c}`).join('|')) {
return word;
}
}
return null;
}, [level]);
useEffect(() => {
isMountedRef.current = true;
return () => {
isMountedRef.current = false;
if (messageTimeoutRef.current) clearTimeout(messageTimeoutRef.current);
if (errorTimeoutRef.current) clearTimeout(errorTimeoutRef.current);
};
}, []);
useEffect(() => {
setLoading(true);
setCompleted(false);
setIsTransitioning(false);
setConfetti([]);
setNewFoundWord(null);
setShowWordModal(false);
setErrorMessage(null);
setAlreadyCompleted(false);
setShowRules(false);
resetAchievements();
completedSentRef.current = false;
perfectStreakRef.current = 0;
startTimeRef.current = Date.now();
// Автопоказ правил при первом входе
if (!rulesShownRef.current) {
rulesShownRef.current = true;
const rulesSeen = localStorage.getItem('filwords_rules_wordsearch');
if (!rulesSeen) {
setTimeout(() => {
if (isMountedRef.current) {
setShowRules(true);
localStorage.setItem('filwords_rules_wordsearch', '1');
}
}, 500);
}
}
getLevel(num)
.then((data: any) => {
if (!isMountedRef.current) return;
setLevel(data.level);
setWords(data.words || []);
if (data.progress?.completed) {
const allWords = (data.words || []).map((w: WordItem) => w.word_pl);
setFoundWords(allWords);
foundWordsRef.current = allWords;
setCompleted(true);
setAlreadyCompleted(true);
const used = data.progress?.first_letter_hints_used || 0;
setFirstLetterHintsUsed(used);
firstLetterHintsUsedRef.current = used;
} else {
setFoundWords([]);
foundWordsRef.current = [];
setFirstLetterHintsUsed(0);
firstLetterHintsUsedRef.current = 0;
}
})
.catch((err: Error) => {
console.error('Error loading level:', err);
if (isMountedRef.current) {
navigate('/menu');
}
})
.finally(() => {
if (isMountedRef.current) {
setLoading(false);
}
});
fetchProgress()
.then((data: any) => {
if (isMountedRef.current) {
setTotalScore(data.total_score || 0);
if (data.current_level) {
setCurrentLevel(data.current_level);
}
}
})
.catch(() => {});
}, [num, navigate, resetAchievements]);
const handleWordFound = useCallback(async (cells: [number, number][]) => {
if (!level || completed || isTransitioning || completedSentRef.current) return;
const foundWord = checkWordMatch(cells);
if (foundWord) {
perfectStreakRef.current += 1;
if (!foundWordsRef.current.includes(foundWord)) {
const newFoundWords = [...foundWordsRef.current, foundWord];
foundWordsRef.current = newFoundWords;
setFoundWords(newFoundWords);
setNewFoundWord(foundWord);
setTimeout(() => {
if (isMountedRef.current) {
setNewFoundWord(null);
}
}, 600);
showMessage(`✅ ${foundWord}`);
if (window.Telegram?.WebApp?.HapticFeedback) {
window.Telegram.WebApp.HapticFeedback.impactOccurred('medium');
}
const allWordsFound = newFoundWords.length === words.length;
if (allWordsFound && !isTransitioning && !completedSentRef.current) {
completedSentRef.current = true;
setIsTransitioning(true);
setCompleted(true);
setConfetti(generateConfetti());
if (window.Telegram?.WebApp?.HapticFeedback) {
window.Telegram.WebApp.HapticFeedback.impactOccurred('heavy');
}
if (!alreadyCompleted) {
try {
const completionTime = Math.floor((Date.now() - startTimeRef.current) / 1000);
const result: any = await completeLevel(
level.id,
firstLetterHintsUsedRef.current,
completionTime,
perfectStreakRef.current
);
if (isMountedRef.current) {
if (!result.already_completed) {
setTotalScore(prev => prev + (result.score || 0));
}
if (result.new_achievements && result.new_achievements.length > 0) {
result.new_achievements.forEach((ach: any) => {
showAchievement({
id: ach.code,
icon: ach.icon,
name: ach.name,
});
});
}
}
} catch (e: any) {
console.error('Error completing level:', e);
if (isMountedRef.current) {
showError(`⚠️ ${e.message || 'Error saving progress'}`);
}
}
}
setTimeout(() => {
if (!isMountedRef.current) return;
const nextLevel = num + 1;
if (nextLevel <= totalLevels) {
navigate(`/play/${nextLevel}`);
} else {
navigate('/menu');
}
}, 2500);
}
}
} else if (cells.length > 1) {
perfectStreakRef.current = 0;
showError(`❌ ${t('wordNotFound')}`);
if (window.Telegram?.WebApp?.HapticFeedback) {
window.Telegram.WebApp.HapticFeedback.impactOccurred('light');
}
}
}, [level, words.length, completed, isTransitioning, alreadyCompleted, num, navigate, generateConfetti, t, checkWordMatch, showAchievement]);
const handleFirstLetterHint = useCallback(() => {
if (!level) return;
if (firstLetterHintsUsedRef.current >= maxFirstLetterHints) {
showError('⚠️ ' + (t('noMoreFirstLetterHints') || 'No more first letter hints'));
return;
}
const newHintsUsed = firstLetterHintsUsedRef.current + 1;
firstLetterHintsUsedRef.current = newHintsUsed;
setFirstLetterHintsUsed(newHintsUsed);
const notFound = words.find(w => !foundWordsRef.current.includes(w.word_pl));
if (notFound) {
const paths = level.word_paths || {};
const path = paths[notFound.word_pl];
if (path && path[0]) {
setFirstLetterCell(path[0] as [number, number]);
setTimeout(() => {
if (isMountedRef.current) {
setFirstLetterCell(null);
}
}, 2000);
}
}
}, [level, words, t]);
const handleShowWords = useCallback(() => {
setShowWordModal(prev => !prev);
}, []);
const showMessage = useCallback((msg: string) => {
if (!isMountedRef.current) return;
setMessage(msg);
if (messageTimeoutRef.current) clearTimeout(messageTimeoutRef.current);
messageTimeoutRef.current = setTimeout(() => {
if (isMountedRef.current) {
setMessage(null);
}
}, 1500);
}, []);
const showError = useCallback((msg: string) => {
if (!isMountedRef.current) return;
setErrorMessage(msg);
if (errorTimeoutRef.current) clearTimeout(errorTimeoutRef.current);
errorTimeoutRef.current = setTimeout(() => {
if (isMountedRef.current) {
setErrorMessage(null);
}
}, 2000);
}, []);
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 (!level) return null;
return (
<div style={{
minHeight: '100vh',
background: bgColor,
color: textColor,
fontFamily: fonts.main,
padding: '16px',
position: 'relative',
overflow: 'hidden',
}}>
<div style={{ position: 'fixed', top: '-80px', left: '-60px', width: '260px', height: '260px', borderRadius: '50%', background: palette.play, opacity: 0.22, filter: 'blur(90px)', pointerEvents: 'none', zIndex: 0 }} />
<div style={{ position: 'fixed', bottom: '-50px', right: '-40px', width: '240px', height: '240px', borderRadius: '50%', background: brandColor, opacity: 0.18, filter: 'blur(80px)', pointerEvents: 'none', zIndex: 0 }} />
<style>{`
@keyframes confettiFall {
0% { transform: translateY(0) rotate(0deg); opacity: 1; }
100% { transform: translateY(100vh) rotate(720deg); opacity: 0; }
}
@keyframes messagePopIn {
0% { opacity: 0; transform: translateX(-50%) translateY(-10px); }
100% { opacity: 1; transform: translateX(-50%) translateY(0); }
}
@keyframes errorShake {
0%, 100% { transform: translateX(-50%); }
25% { transform: translateX(calc(-50% - 5px)); }
75% { transform: translateX(calc(-50% + 5px)); }
}
@keyframes fadeInUp {
0% { transform: translateY(10px); opacity: 0; }
100% { transform: translateY(0); opacity: 1; }
}
@keyframes pulse {
0%, 100% { transform: scale(1); }
50% { transform: scale(1.05); }
}
@keyframes modalFadeIn {
0% { opacity: 0; }
100% { opacity: 1; }
}
@keyframes modalSlideUp {
0% { transform: translateY(30px); opacity: 0; }
100% { transform: translateY(0); opacity: 1; }
}
@keyframes levelCompleteGlow {
0%, 100% { box-shadow: 0 0 15px rgba(76, 217, 100, 0.3); }
50% { box-shadow: 0 0 30px rgba(76, 217, 100, 0.6); }
}
@keyframes achievementSlideDown {
0% { transform: translateX(-50%) translateY(-80px); opacity: 0; }
100% { transform: translateX(-50%) translateY(0); opacity: 1; }
}
`}</style>
<div style={{ position: 'relative', zIndex: 1 }}>
<RulesModal
isOpen={showRules}
onClose={() => setShowRules(false)}
title={t('wordSearchRulesTitle') || '📝 Word Search Rules'}
content={t('wordSearchRulesContent') || 'Rules content loading...'}
/>
{activeAchievement && (
<div style={{
position: 'fixed',
top: '16px',
left: '50%',
transform: 'translateX(-50%)',
zIndex: 900,
background: 'linear-gradient(135deg, #FFD700, #FFA500)',
color: '#FFFFFF',
padding: '14px 20px',
borderRadius: radius.lg,
boxShadow: '0 8px 30px rgba(255, 215, 0, 0.5)',
display: 'flex',
alignItems: 'center',
gap: '12px',
minWidth: '250px',
maxWidth: '90vw',
animation: 'achievementSlideDown 0.4s ease',
}}>
<span style={{ fontSize: '28px', flexShrink: 0 }}>{activeAchievement.icon}</span>
<div>
<div style={{ fontSize: '11px', fontWeight: 600, opacity: 0.9, letterSpacing: '1px', textTransform: 'uppercase' }}>
🏆 {t('achievement') || 'Achievement'}
</div>
<div style={{ fontSize: '15px', fontWeight: 800, marginTop: '2px' }}>
{activeAchievement.name}
</div>
</div>
</div>
)}
{confetti.map((piece) => (
<div
key={piece.id}
style={{
position: 'fixed',
left: `${piece.x}%`,
top: `${piece.y}%`,
width: `${piece.size}px`,
height: `${piece.size * 1.5}px`,
backgroundColor: piece.color,
borderRadius: '2px',
transform: `rotate(${piece.rotation}deg)`,
animation: `confettiFall ${piece.animationDuration}s ease-in ${piece.animationDelay}s forwards`,
zIndex: 1000,
pointerEvents: 'none',
}}
/>
))}
{showWordModal && (
<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',
animation: 'modalFadeIn 0.2s ease',
padding: '20px',
backdropFilter: 'blur(4px)',
WebkitBackdropFilter: 'blur(4px)',
}}
onClick={(e) => {
if (e.target === e.currentTarget) {
setShowWordModal(false);
}
}}
>
<div style={{
...glass({
borderRadius: radius.lg,
padding: '20px',
width: '100%',
maxWidth: '400px',
maxHeight: '70vh',
overflow: 'auto',
}),
boxShadow: '0 20px 60px rgba(31,38,73,0.20), inset 0 1px 0 rgba(255,255,255,0.85)',
animation: 'modalSlideUp 0.3s ease',
}}>
<div style={{
display: 'flex',
justifyContent: 'space-between',
alignItems: 'center',
marginBottom: '16px',
paddingBottom: '12px',
borderBottom: '1px solid rgba(0,0,0,0.06)',
}}>
<h3 style={{ margin: 0, fontSize: '18px', fontWeight: 700, color: textColor }}>
📖 {t('showWords')}
</h3>
<button
onClick={() => setShowWordModal(false)}
style={{
...glass({
padding: '8px 16px',
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)';
}}
>
✕
</button>
</div>
<div style={{ display: 'flex', flexWrap: 'wrap', gap: '10px', justifyContent: 'center' }}>
{words.map((w) => {
const isFound = foundWords.includes(w.word_pl);
return (
<div
key={w.word_pl}
style={{
padding: '10px 14px',
borderRadius: radius.md,
background: isFound
? `${brandColor}20`
: cardBg,
border: `2px solid ${isFound ? brandColor : 'rgba(0,0,0,0.06)'}`,
color: isFound ? '#1a7a3a' : textColor,
fontSize: '14px',
fontWeight: isFound ? 700 : 400,
display: 'flex',
flexDirection: 'column',
alignItems: 'center',
gap: '4px',
minWidth: '80px',
transition: 'all 0.3s ease',
}}
>
<span style={{ fontSize: '16px' }}>{w.word_pl}</span>
{w.translation && (
<span style={{
fontSize: '11px',
color: isFound ? brandColor : subColor,
fontWeight: 400,
}}>
{w.translation}
</span>
)}
{isFound && <span style={{ fontSize: '12px' }}>✅</span>}
</div>
);
})}
</div>
<div style={{
marginTop: '16px',
paddingTop: '12px',
borderTop: '1px solid rgba(0,0,0,0.06)',
textAlign: 'center',
fontSize: '14px',
color: subColor,
}}>
{foundWords.length}/{words.length} {t('foundWords').toLowerCase()}
</div>
</div>
</div>
)}
<div style={{
display: 'flex',
justifyContent: 'space-between',
alignItems: 'center',
marginBottom: '16px',
animation: 'fadeInUp 0.3s ease',
}}>
<div style={{ display: 'flex', gap: '8px', alignItems: 'center' }}>
<button onClick={() => navigate('/menu')}
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>
<button
onClick={() => setShowRules(true)}
style={{
...glass({
width: '40px',
height: '40px',
borderRadius: radius.md,
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
}),
color: textColor,
fontSize: '18px',
fontWeight: 700,
cursor: 'pointer',
transition: 'transform 0.2s ease',
flexShrink: 0,
}}
onTouchStart={(e) => { e.currentTarget.style.transform = 'scale(0.95)'; }}
onTouchEnd={(e) => { e.currentTarget.style.transform = 'scale(1)'; }}
>
?
</button>
</div>
<div style={{ textAlign: 'center' }}>
<div style={{ fontSize: '14px', color: subColor }}>{t('level')} {num}</div>
<div style={{
fontSize: '12px',
color: foundWords.length === words.length ? brandColor : palette.play,
fontWeight: foundWords.length === words.length ? 700 : 400,
}}>
{foundWords.length}/{words.length} {t('foundWords').toLowerCase()}
</div>
</div>
<div style={{ textAlign: 'right', minWidth: '70px', display: 'flex', alignItems: 'center', gap: '8px' }}>
<span style={{
fontSize: '12px',
fontWeight: 800,
color: brandColor,
background: `${brandColor}15`,
padding: '4px 8px',
borderRadius: radius.sm,
border: `1px solid ${brandColor}40`,
}}>
{currentLevel}
</span>
<div>
<div style={{ fontSize: '11px', color: subColor, marginBottom: '2px' }}>{t('score')}</div>
<div style={{ fontSize: '16px', fontWeight: 800, color: brandColor }}>
{totalScore.toLocaleString()}
</div>
</div>
</div>
</div>
{errorMessage && (
<div style={{
position: 'absolute', top: '60px', left: '50%', transform: 'translateX(-50%)',
padding: '10px 20px', fontSize: '14px', fontWeight: 600, color: '#FFFFFF',
background: errorMessage.startsWith('⚠️') ? '#F39C12' : '#E74C3C',
borderRadius: radius.md,
boxShadow: `0 4px 12px ${errorMessage.startsWith('⚠️') ? 'rgba(243,156,18,0.4)' : 'rgba(231,76,60,0.4)'}`,
whiteSpace: 'nowrap', zIndex: 10,
animation: errorMessage.startsWith('⚠️') ? 'messagePopIn 0.25s ease' : 'errorShake 0.4s ease',
}}>
{errorMessage}
</div>
)}
{completed && (
<div style={{
textAlign: 'center', padding: '20px', marginBottom: '12px',
background: `${brandColor}15`,
borderRadius: radius.lg, border: `2px solid ${brandColor}40`,
animation: 'levelCompleteGlow 1.5s ease infinite',
}}>
<div style={{ fontSize: '36px', marginBottom: '8px', animation: 'pulse 0.5s ease 0.2s both' }}>🎉</div>
<div style={{ fontSize: '20px', fontWeight: 700, color: brandColor, animation: 'fadeInUp 0.5s ease 0.3s both' }}>
{alreadyCompleted ? t('alreadyCompleted') || 'Already Completed!' : t('levelCompleted')}
</div>
<div style={{ fontSize: '14px', color: subColor, marginTop: '8px', animation: 'fadeInUp 0.5s ease 0.5s both' }}>
{alreadyCompleted ? (t('alreadyCompletedDesc') || 'This level was completed earlier.') : `${t('loading')}...`}
</div>
{alreadyCompleted && (
<button onClick={() => { const next = num + 1; if (next <= totalLevels) navigate(`/play/${next}`); else navigate('/menu'); }}
style={{ marginTop: '12px', padding: '10px 20px', borderRadius: radius.md, border: 'none', background: `linear-gradient(180deg, ${brandColor}E6, ${brandColor}CC)`, color: '#12271C', fontSize: '14px', fontWeight: 600, cursor: 'pointer', boxShadow: `0 8px 24px ${brandColor}50`, animation: 'fadeInUp 0.5s ease 0.7s both' }}>
{num < totalLevels ? (t('nextLevel') || 'Next Level') + ' →' : (t('backToMenu') || 'Back to Menu')}
</button>
)}
</div>
)}
<div style={{ position: 'relative', marginBottom: '16px' }}>
{message && (
<div style={{
position: 'absolute', top: '-48px', left: '50%', transform: 'translateX(-50%)',
padding: '10px 20px', fontSize: '16px', fontWeight: 700, color: '#FFFFFF',
background: brandColor, borderRadius: radius.md, boxShadow: `0 4px 12px ${brandColor}40`,
whiteSpace: 'nowrap', zIndex: 10, animation: 'messagePopIn 0.25s ease', pointerEvents: 'none',
}}>
{message}
</div>
)}
<div style={{ display: 'flex', justifyContent: 'center' }}>
<LetterGrid
letters={level.grid_letters} gridSize={level.grid_size}
onWordSelect={handleWordFound} foundWords={foundWords}
firstLetterCell={firstLetterCell} wordPaths={level.word_paths || {}}
newFoundWord={newFoundWord}
/>
</div>
</div>
<div style={{ animation: 'fadeInUp 0.3s ease 0.1s both' }}>
<HintPanel
onFirstLetter={handleFirstLetterHint} onShowWords={handleShowWords}
showWordList={showWordModal} firstLetterHintsUsed={firstLetterHintsUsed}
maxFirstLetterHints={maxFirstLetterHints} t={t}
/>
</div>
</div>
</div>
);
};
export default WordSearchPage;