(function() {
    // Конфигурация кнопок
    const CONFIG = {
        targetLiSelector: 'li[data-reactid=".0.1.1.0.1.6"]', // Элемент, после которого вставляем кнопки
        buttons: [
            {
                id: 'custom-btn-h',
                text: 'H',
                title: 'Открыть профиль в Hub',
                bgColor: '#9C27B0', // Сиреневый
                hoverColor: '#7B1FA2',
                getUrl: (uid) => `https://hub.sys5.ru/students/${uid}`
            },
            {
                id: 'custom-btn-dk',
                text: 'ДК',
                title: 'Дорожная карта',
                bgColor: '#03A9F4', // Голубой
                hoverColor: '#0288D1',
                getUrl: (uid) => `https://id.systematika.org/roadmap//live-math/3-4-klass/mini-groups/track1?devStudentId=${uid}`
            },
            {
                id: 'custom-btn-urv2',
                text: 'УРv2',
                title: 'Календарь УРv2',
                bgColor: '#1976D2', // Синий
                hoverColor: '#1565C0',
                getUrl: (uid) => `https://id.systematika.org/calendar/?devStudentId=${uid}`
            }
        ]
    };

    // Функция для получения UID пользователя из URL
    function getUserId() {
        const match = window.location.href.match(/\/id\/(\d+)/);
        return match ? match[1] : null;
    }

    function createButtons(uid) {
        // Если первая кнопка уже есть на странице — прерываем выполнение
        if (document.getElementById(CONFIG.buttons[0].id)) return;

        const targetLi = document.querySelector(CONFIG.targetLiSelector);
        if (!targetLi) return;

        // Переменная для сохранения предыдущего элемента, чтобы вставлять кнопки строго по порядку
        let currentTarget = targetLi;

        CONFIG.buttons.forEach(btnConfig => {
            const newBtn = document.createElement('li');
            newBtn.id = btnConfig.id;
            newBtn.title = btnConfig.title;
            const btnUrl = btnConfig.getUrl(uid);
            
            // Задаем стили контейнеру кнопки
            Object.assign(newBtn.style, {
                margin: '0 2px',
                borderRadius: '4px',
                display: 'inline-flex',
                minWidth: '38px',
                height: '28px',
                background: btnConfig.bgColor,
                transition: 'background 0.2s ease',
                verticalAlign: 'middle',
                boxSizing: 'border-box',
                boxShadow: '0 1px 2px rgba(0,0,0,0.2)'
            });
            
            // Внутрь кладем тег <a>. Это дает нативное поведение (открытие в фоне по колесику мыши)
            newBtn.innerHTML = `
                <a href="${btnUrl}" target="_blank" style="
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    width: 100%;
                    height: 100%;
                    color: #ffffff;
                    font-weight: bold;
                    font-size: 12px;
                    font-family: Arial, sans-serif;
                    text-decoration: none;
                ">${btnConfig.text}</a>
            `;

            // Эффекты при наведении
            newBtn.onmouseenter = () => {
                newBtn.style.background = btnConfig.hoverColor;
            };
            newBtn.onmouseleave = () => {
                newBtn.style.background = btnConfig.bgColor;
            };

            // Вставляем кнопку после текущего целевого элемента
            currentTarget.insertAdjacentElement('afterend', newBtn);
            // Делаем вставленную кнопку новым "целевым элементом" для следующей итерации
            currentTarget = newBtn;
        });
    }

    function removeButtons() {
        CONFIG.buttons.forEach(btnConfig => {
            const btn = document.getElementById(btnConfig.id);
            if (btn) btn.remove();
        });
    }

    function checkAndToggle() {
        const uid = getUserId();
        const targetLi = document.querySelector(CONFIG.targetLiSelector);
        
        // Если мы в профиле пользователя (есть UID) и панель прогрузилась
        if (uid && targetLi) {
            createButtons(uid);
        } else {
            removeButtons();
        }
    }

    // MutationObserver следит за отрисовкой интерфейса (на случай перезагрузки блоков в GetCourse)
    const observer = new MutationObserver(() => {
        checkAndToggle();
    });

    observer.observe(document.body, { 
        childList: true, 
        subtree: true 
    });

    // Стартовая проверка
    checkAndToggle();
})();