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 = { alphabet: '#2ECC71', grammar: '#E74C3C', cheatsheets: '#A970D6', }; const FlashcardsPage: React.FC = () => { const navigate = useNavigate(); const { t, language } = useLanguage(); const [activeTab, setActiveTab] = useState('alphabet'); const [selectedRule, setSelectedRule] = useState(null); const [selectedCheatSheet, setSelectedCheatSheet] = useState(null); const [selectedLetter, setSelectedLetter] = useState(null); const [isPlayingLetter, setIsPlayingLetter] = useState(false); const { activeAchievement, showAchievement } = useAchievements(); const isMountedRef = useRef(true); const audioRef = useRef(null); // 🔧 ФИКС (24.09.2026): URL_LEAK_FLASHCARDS — храним URL для revoke. const audioUrlRef = useRef(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 = { 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; } // 🔧 ФИКС (24.09.2026): URL_LEAK_FLASHCARDS — освобождаем предыдущий URL if (audioUrlRef.current) { try { URL.revokeObjectURL(audioUrlRef.current); } catch { /* ignore */ } audioUrlRef.current = null; } if ('speechSynthesis' in window) { window.speechSynthesis.cancel(); } setIsPlayingLetter(true); try { const audioBlob = await getTTS(word, 'male'); const audioUrl = URL.createObjectURL(audioBlob); audioUrlRef.current = audioUrl; // 🔧 сохраняем для revoke const audio = new Audio(audioUrl); audioRef.current = audio; audio.onended = () => { if (isMountedRef.current) setIsPlayingLetter(false); // 🔧 ФИКС (24.09.2026): освобождаем URL после воспроизведения if (audioUrlRef.current === audioUrl) { try { URL.revokeObjectURL(audioUrl); } catch { /* ignore */ } audioUrlRef.current = null; } }; audio.onerror = () => { // 🔧 Освобождаем URL перед fallback if (audioUrlRef.current === audioUrl) { try { URL.revokeObjectURL(audioUrl); } catch { /* ignore */ } audioUrlRef.current = null; } 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); } }; // 🔧 ФИКС (24.09.2026): FLASHCARDS_RETRACK_ON_ACHIEVEMENT — // вынесли трекинг в отдельный useEffect с [] (одноразовый), // чтобы showAchievement не вызывал повторный трекинг при смене identity. useEffect(() => { window.scrollTo(0, 0); isMountedRef.current = true; return () => { isMountedRef.current = false; if (audioRef.current) { audioRef.current.pause(); audioRef.current = null; } if (audioUrlRef.current) { try { URL.revokeObjectURL(audioUrlRef.current); } catch { /* ignore */ } audioUrlRef.current = null; } if ('speechSynthesis' in window) { window.speechSynthesis.cancel(); } }; }, []); // Одноразовый трекинг при монтировании useEffect(() => { 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(() => {}); // eslint-disable-next-line react-hooks/exhaustive-deps }, []); // 🔧 ИСПРАВЛЕНО: 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 = { pl: 'Zamknij', ru: 'Закрыть', uk: 'Закрити', en: 'Close', }; return labels[language] || labels.en; }; const renderAlphabet = () => (

{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'}

{polishAlphabet.map((letter, i) => { const isDiacritic = polishDiacritics.some(d => d.letter.includes(letter.upper)); return ( ); })}
{selectedLetter !== null && (() => { const letter = polishAlphabet[selectedLetter]; const diacriticInfo = getDiacriticInfo(letter.upper); return (
{ if (e.target === e.currentTarget) setSelectedLetter(null); }} >
{letter.upper} {letter.lower}
{language === 'pl' ? 'Wymowa' : language === 'ru' ? 'Произношение' : language === 'uk' ? 'Вимова' : 'Pronunciation'}: {diacriticInfo ? diacriticInfo.pronunciation : getLocalized(letter, 'pronunciation')}
{diacriticInfo && (
{diacriticInfo.description}
)}
playLetterSound(letter.example_pl)} onTouchStart={(e) => { e.currentTarget.style.transform = 'scale(0.98)'; }} onTouchEnd={(e) => { e.currentTarget.style.transform = 'scale(1)'; }} >
🇵🇱 {letter.example_pl} 🔊
{getLocalizedExample(letter)}
{isPlayingLetter ? (language === 'pl' ? 'Odtwarzanie...' : language === 'ru' ? 'Воспроизведение...' : language === 'uk' ? 'Відтворення...' : 'Playing...') : (language === 'pl' ? 'Kliknij aby usłyszeć' : language === 'ru' ? 'Нажми чтобы услышать' : language === 'uk' ? 'Натисни щоб почути' : 'Tap to hear')}
); })()}
); const renderGrammar = () => (
{grammarRules.map((rule: any) => (
setSelectedRule(rule.id)}>
{getLocalized(rule, 'title')}
))} {selectedRule !== null && (() => { const rule = grammarRules.find((r: any) => r.id === selectedRule); if (!rule) return null; return (
{ if (e.target === e.currentTarget) setSelectedRule(null); }} >

📐 {getLocalized(rule, 'title')}

{getLocalized(rule, 'description').replace(/\\n/g, '\n')}

{language === 'pl' ? (
{rule.example_pl.replace(/\\n/g, '\n')}
) : (
{getLocalized(rule, 'example').replace(/\\n/g, '\n')}
)}
); })()}
); const renderCheatsheets = () => (
{cheatsheets.map((section) => (
setSelectedCheatSheet(section.id)}>
{section.icon} {getLocalized(section, 'title')}
))} {selectedCheatSheet !== null && (() => { const section = cheatsheets.find(s => s.id === selectedCheatSheet); if (!section) return null; return (
{ if (e.target === e.currentTarget) setSelectedCheatSheet(null); }} >

{section.icon} {getLocalized(section, 'title')}

{section.items.map((item, i) => { const content = language === 'pl' ? item.pl : (item[language as keyof typeof item] || item.en || item.pl); return (
{content}
); })}
); })()}
); return (
{activeAchievement && (
{activeAchievement.icon}
🏆 {t('achievement') || 'Achievement'}
{activeAchievement.name}
)}
{tabs.map((tab) => ( ))}
{activeTab === 'alphabet' && renderAlphabet()} {activeTab === 'grammar' && renderGrammar()} {activeTab === 'cheatsheets' && renderCheatsheets()}
); }; export default FlashcardsPage;