import { useState, useEffect, useCallback } from 'react'; import { useLanguage } from '../i18n/LanguageContext'; import { radius } from '../styles/theme'; import { getAdminDashboard, getSentryErrors } from '../api'; import ContentEditorMenu from './ContentEditorMenu'; import WordsEditor from './WordsEditor'; import TextsEditor from './TextsEditor'; import LessonsEditor from './LessonsEditor'; import LessonEditorModal from './LessonEditorModal'; interface AdminDashboardModalProps { isOpen: boolean; onClose: () => void; } interface DashboardData { total_users: number; new_today: number; online_now: number; active_24h: number; level_counts: Record; } interface SentryError { id: string; short_id: string; title: string; culprit: string; level: string; count: number; user_count: number; first_seen: string; last_seen: string; permalink: string; priority: string; } const AdminDashboardModal: React.FC = ({ isOpen, onClose }) => { const { language } = useLanguage(); const [dashboard, setDashboard] = useState(null); const [errors, setErrors] = useState([]); const [errorsLoading, setErrorsLoading] = useState(false); const [errorsError, setErrorsError] = useState(null); const [isLoading, setIsLoading] = useState(true); const [lastUpdate, setLastUpdate] = useState(new Date()); // 🔧 НОВОЕ (19.09.2026): контент-менеджер const [showContentEditor, setShowContentEditor] = useState(false); const [showWordsEditor, setShowWordsEditor] = useState(false); const [showTextsEditor, setShowTextsEditor] = useState(false); const [showLessonsEditor, setShowLessonsEditor] = useState(false); // 🔧 НОВОЕ (19.09.2026): модалка урока (WYSIWYG) const [editingLessonId, setEditingLessonId] = useState(null); const [editingTopicPath, setEditingTopicPath] = useState<{ levelCode: string; topicOrder: number; topicName: string; } | null>(null); const brandColor = '#2ECC71'; const dashColor = '#E8B93F'; const errorColor = '#E74C3C'; const textColor = '#1A1A2E'; const subColor = '#6B7280'; 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 getLabel = (pl: string, ru: string, uk: string, en: string): string => { const labels: Record = { pl, ru, uk, en }; return labels[language] || labels.en; }; const loadData = useCallback(async () => { setIsLoading(true); setErrorsLoading(true); setErrorsError(null); getAdminDashboard() .then((data: DashboardData) => { setDashboard(data); setLastUpdate(new Date()); }) .catch((e) => { console.error('Dashboard error:', e); }) .finally(() => setIsLoading(false)); getSentryErrors() .then((data: any) => { setErrors(data.errors || []); if (data.error) { setErrorsError(data.error); } }) .catch((e) => { console.error('Sentry errors error:', e); setErrorsError('Failed to load errors'); }) .finally(() => setErrorsLoading(false)); }, []); useEffect(() => { if (isOpen) { loadData(); } }, [isOpen, loadData]); // 🔧 ФИКС (23.09.2026): admin_dashboard_no_escape — добавлен обработчик Escape. // Раньше админ-панель закрывалась только кликом на крестик. useEffect(() => { if (!isOpen) return; const handleKey = (e: KeyboardEvent) => { if (e.key === 'Escape') onClose(); }; window.addEventListener('keydown', handleKey); return () => window.removeEventListener('keydown', handleKey); }, [isOpen, onClose]); const formatDate = (isoStr: string): string => { try { const date = new Date(isoStr); const now = new Date(); const diffMs = now.getTime() - date.getTime(); const diffMin = Math.floor(diffMs / 60000); const diffHr = Math.floor(diffMin / 60); const diffDay = Math.floor(diffHr / 24); if (diffMin < 1) return getLabel('teraz', 'только что', 'щойно', 'just now'); if (diffMin < 60) return `${diffMin} ${getLabel('min temu', 'мин назад', 'хв тому', 'min ago')}`; if (diffHr < 24) return `${diffHr} ${getLabel('godz. temu', 'ч назад', 'год тому', 'h ago')}`; if (diffDay < 30) return `${diffDay} ${getLabel('dni temu', 'дн назад', 'дн тому', 'd ago')}`; return date.toLocaleDateString(); } catch { return isoStr; } }; const getLevelColor = (level: string): string => { const colors: Record = { A1: '#2ECC71', A2: '#27AE60', B1: '#F39C12', B2: '#E67E22', C1: '#E74C3C', C2: '#C0392B', }; return colors[level] || brandColor; }; const maxLevelCount = dashboard ? Math.max(...Object.values(dashboard.level_counts), 1) : 1; if (!isOpen) return null; return ( <>
{ if (e.target === e.currentTarget) onClose(); }} >
e.stopPropagation()} > {/* Заголовок */}
📊

{getLabel('Panel admina', 'Админ-панель', 'Адмін-панель', 'Admin Panel')}

{isLoading && !dashboard ? (
{getLabel('Ładowanie...', 'Загрузка...', 'Завантаження...', 'Loading...')}
) : ( <> {/* 🔧 НОВОЕ (19.09.2026): кнопка Контент-менеджер — сверху, зелёная */}
{/* ============ СЕКЦИЯ 1: СТАТИСТИКА ============ */}
👥 {getLabel('Statystyki', 'Статистика', 'Статистика', 'Statistics')}
{getLabel('Wszyscy', 'Всего', 'Всього', 'Total')}
{dashboard?.total_users ?? 0}
🆕 {getLabel('Nowi dziś', 'Новых сегодня', 'Нових сьогодні', 'New today')}
{dashboard?.new_today ?? 0}
🟢 {getLabel('Online', 'Онлайн', 'Онлайн', 'Online')}
{dashboard?.online_now ?? 0}
📈 {getLabel('Aktywni 24h', 'Активных 24ч', 'Активних 24г', 'Active 24h')}
{dashboard?.active_24h ?? 0}
{/* ============ СЕКЦИЯ 2: ПО УРОВНЯМ ============ */}
🎯 {getLabel('Poziomy', 'Уровни', 'Рівні', 'Levels')}
{dashboard && Object.entries(dashboard.level_counts).map(([level, count]) => { const percent = count > 0 ? (count / maxLevelCount) * 100 : 0; return (
{level} 0 ? textColor : subColor }}>{count}
); })}
{/* ============ СЕКЦИЯ 3: ОШИБКИ SENTRY ============ */}
0 ? errorColor : dashColor, letterSpacing: '0.5px', textTransform: 'uppercase', }}> ⚠️ {getLabel('Błędy', 'Ошибки', 'Помилки', 'Errors')} ({errors.length})
{getLabel('Otwórz Sentry', 'Открыть Sentry', 'Відкрити Sentry', 'Open Sentry')} ↗
{errorsLoading ? (
{getLabel('Ładowanie...', 'Загрузка...', 'Завантаження...', 'Loading...')}
) : errorsError ? (
{errorsError}
) : errors.length === 0 ? (
✅ {getLabel('Brak błędów', 'Ошибок нет', 'Помилок немає', 'No errors')}
) : ( )}
{/* Футер */}
{getLabel('Aktualizacja', 'Обновлено', 'Оновлено', 'Updated')}: {lastUpdate.toLocaleTimeString()}
)}
{/* 🔧 НОВОЕ (19.09.2026): модалка контент-менеджера */} setShowContentEditor(false)} onNavigate={(section) => { setShowContentEditor(false); if (section === 'words') { setShowWordsEditor(true); } else if (section === 'texts') { setShowTextsEditor(true); } else if (section === 'lessons') { setShowLessonsEditor(true); } }} /> setShowWordsEditor(false)} /> setShowTextsEditor(false)} /> {/* 🔧 НОВОЕ (19.09.2026): Уроки — иерархия */} { setShowLessonsEditor(false); setEditingLessonId(null); setEditingTopicPath(null); }} onOpenLesson={(lessonId, topicPath) => { setEditingLessonId(lessonId); setEditingTopicPath(topicPath); }} /> {/* 🔧 НОВОЕ (19.09.2026): WYSIWYG-модалка урока */} { setEditingLessonId(null); setEditingTopicPath(null); }} onSaved={() => { setEditingLessonId(null); setEditingTopicPath(null); }} /> ); }; export default AdminDashboardModal;