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([]); const [bubbles, setBubbles] = useState([]); 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([]); const [foundWords, setFoundWords] = useState([]); const [completed, setCompleted] = useState(false); const [isTransitioning, setIsTransitioning] = useState(false); const [showRules, setShowRules] = useState(false); const [message, setMessage] = useState(null); const [errorMessage, setErrorMessage] = useState(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(null); const { activeAchievement, showAchievement, resetAchievements } = useAchievements(); const isMountedRef = useRef(true); const messageTimeoutRef = useRef | null>(null); const hintTimeoutRef = useRef | null>(null); // 🔧 ФИКС (23.09.2026): BUBBLE_ERROR_MESSAGE_STUCK — добавлен таймер для errorMessage, // чтобы плашка автоскрывалась (раньше висела бесконечно). const errorTimeoutRef = useRef | null>(null); const startTimeRef = useRef(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); // 🔧 ФИКС (23.09.2026): BUBBLE_ERROR_MESSAGE_STUCK — cleanup нового таймера if (errorTimeoutRef.current) clearTimeout(errorTimeoutRef.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); }; // 🔧 ФИКС (23.09.2026): BUBBLE_ERROR_MESSAGE_STUCK — helper для errorMessage // с автоскрытием через 2 секунды (по аналогии с showMessage). const showError = (msg: string) => { if (!isMountedRef.current) return; setErrorMessage(msg); if (errorTimeoutRef.current) clearTimeout(errorTimeoutRef.current); errorTimeoutRef.current = setTimeout(() => { if (isMountedRef.current) setErrorMessage(null); }, 2000); }; 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 = {}; 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) { // 🔧 ФИКС (23.09.2026): BUBBLE_ERROR_MESSAGE_STUCK — используем showError showError('⚠️ ' + (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 (
{t('loading')}...
); } return (
setShowRules(false)} title={t('bubbleWordsRulesTitle') || '🫧 Bubble Words Rules'} content={t('bubbleWordsRulesContent') || 'Rules content loading...'} /> {activeAchievement && (
{activeAchievement.icon}
🏆 {t('achievement') || 'Achievement'}
{activeAchievement.name}
)}
{t('level')} {bubbleLevel}
{currentLevel}
{t('score')}
{totalScore}
{errorMessage && (
{errorMessage}
)} {message && (
{message}
)}
{foundWords.map(w => ( ✅ {w} ))}
{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 (
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}
); })}
{selectedBubbles.length > 0 && (
{selectedBubbles.map((b, i) => ( {b.text} ))}
)}
{showWordModal && (
{ if (e.target === e.currentTarget) setShowWordModal(false); }} >

📖 {t('showWords')}

{words.map(w => (
{w.word_pl} {w.translation && ( {w.translation} )} {foundWords.includes(w.word_pl) && ✅}
))}
{foundWords.length}/{words.length} {t('foundWords').toLowerCase()}
)} {completed && (
🎉
{t('levelCompleted')}
)}
{t('levelsCompleted')}: {levelsCompleted}
); }; export default BubbleWordsPage;