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 = { 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(null); const [loading, setLoading] = useState(true); const [isPlaying, setIsPlaying] = useState(false); const [showRules, setShowRules] = useState(false); const audioRef = useRef(null); // 🔧 ФИКС (24.09.2026): URL_LEAK_PRONUNCIATION — храним URL для revoke. const audioUrlRef = useRef(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; } // 🔧 ФИКС (24.09.2026): URL_LEAK_PRONUNCIATION — освобождаем предыдущий URL if (audioUrlRef.current) { try { URL.revokeObjectURL(audioUrlRef.current); } catch { /* ignore */ } audioUrlRef.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); audioUrlRef.current = audioUrl; // 🔧 сохраняем для revoke const audio = new Audio(audioUrl); audioRef.current = audio; audio.onended = () => { if (isMountedRef.current) setIsPlaying(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; } // 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; } // 🔧 ФИКС (24.09.2026): URL_LEAK_PRONUNCIATION — освобождаем URL при unmount if (audioUrlRef.current) { try { URL.revokeObjectURL(audioUrlRef.current); } catch { /* ignore */ } audioUrlRef.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 (
{t('loading')}...
); } return (
setShowRules(false)} title={t('pronunciationRulesTitle') || '🔊 Pronunciation Rules'} content={t('pronunciationRulesContent') || 'Rules content loading...'} /> {activeAchievement && (
{activeAchievement.icon}
🏆 {t('achievement') || 'Achievement'}
{activeAchievement.name}
)} {/* Верхняя панель */}
{currentWord?.level}
{/* Заголовок */}

🔊 {t('pronunciation') || 'Pronunciation'}

{t('tapToListen') || 'Tap the word to listen'}

{/* Карточка со словом */} {currentWord && (
playWord(currentWord.word_pl)} onTouchStart={(e) => { e.currentTarget.style.transform = 'scale(0.98)'; }} onTouchEnd={(e) => { e.currentTarget.style.transform = 'scale(1)'; }} > {/* Иконка динамика */}
🔊
{/* Польское слово */}
{currentWord.word_pl}
{/* Разделитель */}
{/* Перевод */}
{currentWord.translation}
{/* Индикатор воспроизведения */} {isPlaying && (
{[0, 1, 2, 3, 4].map((i) => (
))}
)}
)} {/* Кнопка Далее */}
); }; export default PronunciationPage;