// Основные константы и утилиты
const GC_DOMAINS = /https:\/\/(npipl\.getcourse\.ru|gc\.psy-person\.ru)/;
const STREAM_PATHS = /^\/teach\/control(\/stream(\/index)?)?\/?$/;
const STREAM_VIEW_PATH = /^\/teach\/control\/stream\/view\/id\/\d+/;

// Общие функции
const isStreamPage = () => STREAM_PATHS.test(window.location.pathname);
const isStreamViewPage = () => STREAM_VIEW_PATH.test(window.location.pathname);
const isControlPage = () => GC_DOMAINS.test(window.location.href) && isStreamPage();

// Удаление точки из кол-ва уроков и замена текста
function processStreamElements() {
    const $elements = $('.stream-table tr td div b');
    
    if ($elements.length === 0) return;
    
    // Удаление точек из чисел
    $elements.each(function() {
        let text = $(this).text().replace('.', '');
        $(this).text(text);
    });
    
    // Замена слова "урок" на соответствующие варианты
    if (isStreamPage()) {
        const wordMap = {
            'урок': 'дисциплина',
            'урока': 'дисциплины', 
            'уроков': 'дисциплин'
        };
        replaceWords($elements, wordMap);
    }
    
    if (isStreamViewPage()) {
        const wordMap = {
            'урок': 'занятие',
            'урока': 'занятия',
            'уроков': 'занятий'
        };
        replaceWords($elements, wordMap);
    }
}

// Замена слов в тексте элементов
function replaceWords($elements, wordMap) {
    $elements.each(function() {
        let text = $(this).text().trim();
        const words = text.split(/\s+/);
        const replacedWords = words.map(word => wordMap[word] || word);
        $(this).text(replacedWords.join(' '));
    });
}

// Замена навигации "урок" на "занятие"
function updateLessonNavigation() {
    document.querySelectorAll('.row.lesson-navigation a').forEach(link => {
        const text = link.textContent.trim();
        if (text === 'Предыдущий урок') {
            link.textContent = 'Предыдущее занятие';
        } else if (text === 'Следующий урок') {
            link.textContent = 'Следующее занятие';
        }
    });
}

// Корректировка количества дисциплин для разных программ
function updateProgramDisciplines() {
    if (!isControlPage()) return;
    
    const updates = [
        {
            pattern: 'Основы психологии (нулевой курс)',
            newText: '11 дисциплин'
        },
        {
            pattern: 'Практическая христианская психология', 
            newText: '10 дисциплин'
        },
        {
            pattern: 'Внутренний ребёнок. Психология взросления',
            newText: '25 занятий / 6 интенсивов'
        },
        {
            pattern: 'Психология и религия',
            newText: '3 модуля'
        },
        {
            pattern: 'Психология и религия (ознакомительная встреча)',
            newText: 'Доступна запись',
            style: {
                background: 'transparent',
                border: '2px solid #FFCA86'
            }
        }
    ];
    
    document.querySelectorAll('.stream-table tr td').forEach(element => {
        updates.forEach(update => {
            if (element.textContent.includes(update.pattern)) {
                const targetElement = element.querySelector('div b');
                if (targetElement) {
                    targetElement.textContent = update.newText;
                    if (update.style) {
                        Object.assign(targetElement.style, update.style);
                    }
                }
            }
        });
    });
}

// Обработка дат уроков
function processLessonDates() {
    // Удаление фразы "Дата и время начала"
    $('.user-state-label.has-start-at.lesson-date').each(function() {
        let text = $(this).text().replace('Дата и время начала', '').trim();
        $(this).text(text);
    });
    
    // Замена даты 1899 года на "Доступна запись"
    document.querySelectorAll('.user-state-label.has-start-at.lesson-date').forEach(element => {
        if (element.textContent.includes('Дата начала Вс 31 Дек 1899')) {
            element.textContent = 'Доступна запись';
            element.style.background = 'transparent';
            element.style.border = '2px solid #FFCA86';
        }
    });
}

// Удаление ссылок из расписания
function removeScheduleLinks() {
    $('.schedule-block .event a').attr('href', '');
}

// Замена текста в хлебных крошках
function updateBreadcrumbs() {
    // Замена "Тренинги" на "Программы"
    $('.breadcrumbs a').filter(function() {
        return $(this).text() === 'Тренинги';
    }).text('Программы');
    
    // Замена "Список тренингов" на "Список программ"  
    $('.standard-page-content .breadcrumb a').filter(function() {
        return $(this).text() === 'Список тренингов';
    }).text('Список программ');
}

// Основная функция инициализации
function initAllScripts() {
    // jQuery функции
    $(document).ready(function() {
        processStreamElements();
        processLessonDates();
        removeScheduleLinks();
        updateBreadcrumbs();
    });
    
    // Pure JS функции
    document.addEventListener('DOMContentLoaded', function() {
        updateLessonNavigation();
        updateProgramDisciplines();
    });
}

// Запуск всех скриптов
initAllScripts();