Files
filwordspl-frontend/src/pages/FlashcardsPage.tsx
T
2026-09-20 15:08:32 +03:00

711 lines
27 KiB
TypeScript

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;