import React, { useState, useEffect, useRef } from 'react' import { useAuth } from './auth/AuthContext' import LoadingError from './LoadingError' import './TestConfigSelection.css' const API_URL = '/api' function TestConfigSelection({ onNavigate, refreshTrigger = 0 }) { const { authFetch } = useAuth() const [configs, setConfigs] = useState([]) const [dictionaries, setDictionaries] = useState([]) const [loading, setLoading] = useState(true) const [error, setError] = useState('') const [selectedConfig, setSelectedConfig] = useState(null) const [selectedDictionary, setSelectedDictionary] = useState(null) const [longPressTimer, setLongPressTimer] = useState(null) const isInitializedRef = useRef(false) const configsRef = useRef([]) const dictionariesRef = useRef([]) // Обновляем ref при изменении состояния useEffect(() => { configsRef.current = configs }, [configs]) useEffect(() => { dictionariesRef.current = dictionaries }, [dictionaries]) useEffect(() => { fetchTestConfigsAndDictionaries() }, [refreshTrigger]) const fetchTestConfigsAndDictionaries = async () => { try { // Показываем загрузку только при первой инициализации или если нет данных для отображения const isFirstLoad = !isInitializedRef.current const hasData = !isFirstLoad && (configsRef.current.length > 0 || dictionariesRef.current.length > 0) if (!hasData) { setLoading(true) } const response = await authFetch(`${API_URL}/test-configs-and-dictionaries`) if (!response.ok) { throw new Error('Ошибка при загрузке конфигураций и словарей') } const data = await response.json() setConfigs(Array.isArray(data.configs) ? data.configs : []) setDictionaries(Array.isArray(data.dictionaries) ? data.dictionaries : []) setError('') isInitializedRef.current = true } catch (err) { setError(err.message) setConfigs([]) setDictionaries([]) isInitializedRef.current = true } finally { setLoading(false) } } const handleConfigSelect = (config) => { onNavigate?.('test', { wordCount: config.words_count, configId: config.id, maxCards: config.max_cards || null }) } const handleDictionarySelect = (dict) => { // For now, navigate to words list // In the future, we might want to filter by dictionary_id onNavigate?.('words', { dictionaryId: dict.id }) } const handleConfigMenuClick = (config, e) => { e.stopPropagation() setSelectedConfig(config) } const handleDictionaryMenuClick = (dict, e) => { e.stopPropagation() setSelectedDictionary(dict) } const handleEdit = () => { if (selectedConfig) { onNavigate?.('add-config', { config: selectedConfig }) setSelectedConfig(null) } } const handleDictionaryDelete = async () => { if (!selectedDictionary) return try { const response = await authFetch(`${API_URL}/dictionaries/${selectedDictionary.id}`, { method: 'DELETE', headers: { 'Content-Type': 'application/json', }, }) if (!response.ok) { const errorText = await response.text() console.error('Delete error:', response.status, errorText) throw new Error(`Ошибка при удалении словаря: ${response.status}`) } setSelectedDictionary(null) // Refresh dictionaries list await fetchTestConfigsAndDictionaries() } catch (err) { console.error('Delete failed:', err) setError(err.message) setSelectedDictionary(null) } } const handleDelete = async () => { if (!selectedConfig) return try { const response = await authFetch(`${API_URL}/configs/${selectedConfig.id}`, { method: 'DELETE', headers: { 'Content-Type': 'application/json', }, }) if (!response.ok) { const errorText = await response.text() console.error('Delete error:', response.status, errorText) throw new Error(`Ошибка при удалении конфигурации: ${response.status}`) } setSelectedConfig(null) // Refresh configs and dictionaries list await fetchTestConfigsAndDictionaries() } catch (err) { console.error('Delete failed:', err) setError(err.message) setSelectedConfig(null) } } const closeModal = () => { setSelectedConfig(null) } // Показываем загрузку только при первой инициализации и если нет данных для отображения const shouldShowLoading = loading && !isInitializedRef.current && configs.length === 0 && dictionaries.length === 0 if (shouldShowLoading) { return (