/*(function() {
    console.log('@check-lesson 1.o1 started');
    // Проверка URL и извлечение lessonId
    const url = window.location.href;
    const urlParams = new URLSearchParams(window.location.search);
    const lessonId = urlParams.get('id');
    
    // Проверка на правильный URL
    if (!lessonId || (!url.includes('/pl/teach/control/lesson/view') && !url.includes('/pl/teach/control/lesson/webview'))) {
        return;
    }

    const endpoint = '/chtm/database-for-levels'; // Укажи корректный URL, если он отличается

    // Проверяем информацию о пользователе (userInfo)
    

    // Если пользователь - админ, выводим сообщение и выходим из скрипта
   if( userInfo.isAdmin || userInfo.isTeacher) { 
        
        console.log('Это админ или учитель')
    	return
    } 

    // Отправка GET-запроса на эндпоинт
    fetch(`${endpoint}?lessonId=${lessonId}`)
        .then(response => response.json())
        .then(data => {
            console.log('Статус по уроку:', data.status);  // Выводим ответ в консоль

            // Если доступ разрешен или уровень не задан, ничего не делаем
            if (data.status.access) {
                
                console.log('Есть доступ, список уроков уровня')
                console.log(data.levelLessons)
                return;
            }
 if (userInfo.isAdmin) {
        console.log("Не перелистываем дальше, потому что вы админ");
      	console.log('Есть доступ, список уроков уровня')
     	console.log(data.levelLessons)
        return;
    }
            // Если доступ запрещен, скрываем содержимое страницы
            const mainContent = document.querySelector('.gc-main-content');
            const lessonContent = document.querySelector('.lesson-content');

            if (mainContent) {
                mainContent.style.transition = 'opacity 0.5s';
                mainContent.style.opacity = '0';
            }

            if (lessonContent) {
                lessonContent.style.transition = 'opacity 0.5s';
                lessonContent.style.opacity = '0';
            }

            // Функция для обработки случая, когда нужно кликнуть по ссылке "Следующий урок"
            function clickNextLessonOrRedirect() {
                const nextLessonLink = Array.from(document.querySelectorAll('a')).find(link => link.textContent.includes('Следующий урок'));

                if (nextLessonLink) {
                    nextLessonLink.click();
                } else {
                    // Если ссылка "Следующий урок" не найдена, делаем редирект на страницу тренинга
                    window.location.href = `/teach/control/stream/view/id/${data.trainingId}`;
                }
            }

            // Интервал для проверки наличия ссылок
            const intervalId = setInterval(() => {
                const nextLessonLink = document.querySelector('a:contains("Следующий урок")');
                if (nextLessonLink) {
                    clickNextLessonOrRedirect();
                    clearInterval(intervalId);
                }
            }, 500); // Проверяем каждые 500 мс

            // Устанавливаем таймер на 5 секунд для гарантированной проверки и выполнения редиректа
            setTimeout(() => {
                clearInterval(intervalId); // Останавливаем интервал
                clickNextLessonOrRedirect();
            }, 5000); // 5 секунд ожидания, можно настроить
        })
        .catch(error => console.error('Error:', error));
})(); */


(function() {
    console.log('@check-lesson 1.10 started');
    // Проверка URL и извлечение lessonId
    const url = window.location.href;
    const urlParams = new URLSearchParams(window.location.search);
    const lessonId = urlParams.get('id');
    
    // Проверка на правильный URL
    if (!lessonId || (!url.includes('/pl/teach/control/lesson/view') && !url.includes('/pl/teach/control/lesson/webview'))) {
        return;
    }
    
    if( userInfo.isAdmin || userInfo.isTeacher) { 
        
        console.log('Это админ или учитель')
    	return
    } 
    
    const endpoint = '/chtm/database-for-levels';
    
    // Функция для поиска соседних уроков (предыдущий и следующий) доступных для уровня пользователя
    function findAdjacentLessons(currentLessonId, lessonList, userLevel, currentLessonNumber) {
        // Сортируем уроки по номеру урока
        const sortedLessons = [...lessonList].sort((a, b) => a.lesson_number - b.lesson_number);
        
        // Найдем текущий урок
        const currentIndex = sortedLessons.findIndex(lesson => lesson.lessonId === currentLessonId);
        
        // Доступные для пользователя уроки
        const availableLessons = sortedLessons.filter(lesson => {
            const lessonLevels = lesson.level.split(',').map(l => l.trim());
            return lessonLevels.includes(userLevel) || lessonLevels.some(l => parseInt(l) <= parseInt(userLevel));
        });
        
        // Если текущий урок не найден, но у нас есть его номер
        if (currentIndex === -1 && currentLessonNumber) {
            console.log("Текущий урок не найден в списке, используем номер урока:", currentLessonNumber);
            
            // Инициализируем результаты
            let prevLesson = null;
            let nextLesson = null;
            
            // Ищем ближайший предыдущий доступный урок
            for (const lesson of [...availableLessons].sort((a, b) => b.lesson_number - a.lesson_number)) {
                if (lesson.lesson_number < currentLessonNumber) {
                    prevLesson = lesson;
                    break;
                }
            }
            
            // Ищем ближайший следующий доступный урок
            for (const lesson of availableLessons) {
                if (lesson.lesson_number > currentLessonNumber) {
                    nextLesson = lesson;
                    break;
                }
            }
            
            return { prev: prevLesson, next: nextLesson };
        }
        
        // Если урок найден в списке
        if (currentIndex !== -1) {
            console.log("Текущий урок найден, индекс:", currentIndex);
            
            // Инициализируем результаты
            let prevLesson = sortedLessons[currentIndex-1];
            let nextLesson = sortedLessons[currentIndex+1];
            
           /* // Ищем предыдущий доступный урок
            for (let i = currentIndex - 1; i >= 0; i--) {
                const lesson = sortedLessons[i];
                const lessonLevels = lesson.level.split(',').map(l => l.trim());
                
                if (lessonLevels.includes(userLevel) || lessonLevels.some(l => parseInt(l) <= parseInt(userLevel))) {
                    prevLesson = lesson;
                    break;
                }
            }
            
            // Ищем следующий доступный урок
            for (let i = currentIndex + 1; i < sortedLessons.length; i++) {
                const lesson = sortedLessons[i];
                const lessonLevels = lesson.level.split(',').map(l => l.trim());
                
                if (lessonLevels.includes(userLevel) || lessonLevels.some(l => parseInt(l) <= parseInt(userLevel))) {
                    nextLesson = lesson;
                    break;
                }
            } */
            
            return { prev: prevLesson, next: nextLesson };
        }
        
        // Если урок не найден и номер не известен
        console.log("Текущий урок не найден в списке и номер урока неизвестен");
        return { prev: null, next: availableLessons[0] || null }; // Возвращаем первый доступный урок как следующий
    }
    
    // Функция для обновления ссылок навигации
    function updateNavigationLinks(prevLesson, nextLesson) {
        // Определяем, используется ли webview
        const isWebView = url.includes('/webview');
        const viewType = isWebView ? 'webview' : 'view';
        
        // Ищем ссылки на предыдущий и следующий урок
        const allLinks = Array.from(document.querySelectorAll('a'));
        
        const prevLessonLink = allLinks.find(link => 
            link.textContent.includes('Предыдущий урок') || 
            link.textContent.includes('Пред. урок'));
            
        const nextLessonLink = allLinks.find(link => 
            link.textContent.includes('Следующий урок') || 
            link.textContent.includes('След. урок'));
        
        // Для отладки
        console.log('Найдены ссылки:', { 
            prevLessonLinkFound: !!prevLessonLink, 
            nextLessonLinkFound: !!nextLessonLink 
        });
        
        // Обновляем ссылку на предыдущий урок, если она найдена и есть предыдущий урок
        if (prevLessonLink && prevLesson) {
            prevLessonLink.href = `/pl/teach/control/lesson/${viewType}?id=${prevLesson.lessonId}`;
            console.log('Обновлена ссылка на предыдущий урок:', prevLesson.lessonId);
            
            // Удаляем атрибуты, которые могут блокировать переход
            prevLessonLink.removeAttribute('disabled');
            prevLessonLink.style.pointerEvents = 'auto';
            prevLessonLink.style.opacity = '1';
        } else if (prevLessonLink) {
            console.log('Предыдущий урок не найден, ссылка не обновлена');
            // Опционально: можно скрыть или деактивировать ссылку
            prevLessonLink.style.pointerEvents = 'none';
            prevLessonLink.style.opacity = '0.5';
        }
        
        // Обновляем ссылку на следующий урок, если она найдена и есть следующий урок
        if (nextLessonLink && nextLesson) {
            nextLessonLink.href = `/pl/teach/control/lesson/${viewType}?id=${nextLesson.lessonId}`;
            console.log('Обновлена ссылка на следующий урок:', nextLesson.lessonId);
            
            // Удаляем атрибуты, которые могут блокировать переход
            nextLessonLink.removeAttribute('disabled');
            nextLessonLink.style.pointerEvents = 'auto';
            nextLessonLink.style.opacity = '1';
        } else if (nextLessonLink) {
            console.log('Следующий урок не найден, ссылка не обновлена');
            // Опционально: можно скрыть или деактивировать ссылку
            nextLessonLink.style.pointerEvents = 'none';
            nextLessonLink.style.opacity = '0.5';
        }
        
        return { prevLessonLink, nextLessonLink };
    }
    
    // Отправка GET-запроса на эндпоинт
    fetch(`${endpoint}?lessonId=${lessonId}`)
        .then(response => response.json())
        .then(data => {
            console.log('Статус по уроку:', data.status);
            console.log('Список уроков уровня:', data.levelLessons);
            
            // Если доступ разрешен, обновляем навигационные ссылки
            if (data.status.access) {
                const userLevel = data.status.userLevel;
                
                // Находим предыдущий и следующий уроки для текущего уровня пользователя
                const lessonNumber = data.status.lesson_number;
                const adjacentLessons = findAdjacentLessons(lessonId, data.levelLessons, userLevel, lessonNumber);
                console.log('Соседние уроки:', adjacentLessons);
                
                // Обновляем навигационные ссылки
                updateNavigationLinks(adjacentLessons.prev, adjacentLessons.next);
                return;
            }
            
            // Проверка для администраторов
            if (window.userInfo && window.userInfo.isAdmin) {
                console.log("Не перелистываем дальше, потому что вы админ");
                
                // Преобразуем номера уроков в числа для корректной сортировки
                data.levelLessons.forEach(lesson => {
                    lesson.lesson_number = parseInt(lesson.lesson_number);
                });
                
                // Находим предыдущий и следующий уроки
                const lessonNumber = data.status.lesson_number;
                const adjacentLessons = findAdjacentLessons(lessonId, data.levelLessons, "5", lessonNumber); // для админа максимальный уровень
                console.log('Соседние уроки для админа:', adjacentLessons);
                
                // Обновляем навигационные ссылки
                updateNavigationLinks(adjacentLessons.prev, adjacentLessons.next);
                
                // Выводим результаты для отладки
                console.log('Результат findAdjacentLessons для админа:', {
                    prevFound: !!adjacentLessons.prev,
                    nextFound: !!adjacentLessons.next,
                    prevId: adjacentLessons.prev ? adjacentLessons.prev.lessonId : null,
                    nextId: adjacentLessons.next ? adjacentLessons.next.lessonId : null
                });
                
                return;
            }
            
            // Если доступ запрещен, скрываем содержимое страницы
            const mainContent = document.querySelector('.gc-main-content');
            const lessonContent = document.querySelector('.lesson-content');
            if (mainContent) {
                mainContent.style.transition = 'opacity 0.5s';
                mainContent.style.opacity = '0';
            }
            if (lessonContent) {
                lessonContent.style.transition = 'opacity 0.5s';
                lessonContent.style.opacity = '0';
            }
            
            // Находим следующий доступный урок для перенаправления
            const userLevel = data.status.userLevel;
            const lessonNumber = data.status.lesson_number;
            const adjacentLessons = findAdjacentLessons(lessonId, data.levelLessons, userLevel, lessonNumber);
            
            // Функция для перенаправления на следующий урок или главную страницу курса
            function redirectToNextLessonOrTraining() {
                // Определяем правильный URL в зависимости от текущего URL
                const isWebView = url.includes('/webview');
                const viewType = isWebView ? 'webview' : 'view';
                
                if (adjacentLessons.next) {
                    // Перенаправляем на следующий доступный урок
                    window.location.href = `/pl/teach/control/lesson/${viewType}?id=${adjacentLessons.next.lessonId}`;
                } else {
                    // Если следующего урока нет, перенаправляем на страницу тренинга
                    // Для webview используется другой формат URL
                    if (isWebView) {
                        window.location.href = `/pl/teach/control/stream/${viewType}/id/${data.status.trainingId}`;
                    } else {
                        window.location.href = `/teach/control/stream/view/id/${data.status.trainingId}`;
                    }
                }
            }
            
            // Запускаем перенаправление через 3 секунды
            setTimeout(redirectToNextLessonOrTraining, 3000);
        })
        .catch(error => {
            console.error('Error:', error);
            // В случае ошибки можно добавить дополнительную логику обработки
        });
})();