(function() {
    const CONFIG = {
        targetLiSelector: 'li[data-reactid=".0.1.1.0.1.6"]',
        emailSelector: 'span[data-reactid=".0.1.1.0.0.2.3.1"]',
        infoBoxSelector: '#userinfo_content',
        triggerText: 'Пользователь не найден в MoyKlass.',
        btnId: 'create-mk-user-custom-btn',
        existingMkBtnSelector: '#moyklass_link',
        endpoint: 'https://online.systematika.org/chtm/app/builder/event/~reg/hcYnny81bzL2iLkD3OpezMvKe/ygF0k8ERF0'
    };

    function showToast(message) {
        const toast = document.createElement('div');
        toast.textContent = message;
        Object.assign(toast.style, {
            position: 'fixed',
            bottom: '30px',
            right: '30px',
            background: 'rgba(50, 50, 50, 0.9)',
            color: '#fff',
            padding: '15px 25px',
            borderRadius: '8px',
            zIndex: '10000',
            fontSize: '14px',
            boxShadow: '0 5px 15px rgba(0,0,0,0.3)',
            transition: 'opacity 0.5s ease',
            pointerEvents: 'none'
        });
        document.body.appendChild(toast);
        setTimeout(() => {
            toast.style.opacity = '0';
            setTimeout(() => toast.remove(), 500);
        }, 3000);
    }

    function createBtn(email) {
        if (document.getElementById(CONFIG.btnId)) return;

        const targetLi = document.querySelector(CONFIG.targetLiSelector);
        if (!targetLi) return;

        const newBtn = document.createElement('li');
        newBtn.id = CONFIG.btnId;
        newBtn.title = 'Создать пользователя в MoyKlass';
        
        Object.assign(newBtn.style, {
            cursor: 'pointer',
            margin: '0 2px',
            border: '1px solid #d4d4d4',
            borderRadius: '4px',
            display: 'inline-flex',
            alignItems: 'center',
            justifyContent: 'center',
            padding: '4px 20px',
            minWidth: '80px',
            background: '#fff',
            transition: 'all 0.2s ease',
            verticalAlign: 'middle',
            boxSizing: 'border-box'
        });
        
        newBtn.innerHTML = `
            <span style="display: flex; align-items: center; gap: 8px; pointer-events: none;">
                <span style="font-size: 16px; color: #555;">&#128100;</span>
                <span style="font-size: 18px; font-weight: bold; color: #4CAF50;">+</span>
            </span>
        `;

        newBtn.onmouseenter = () => {
            newBtn.style.background = '#f9f9f9';
            newBtn.style.borderColor = '#aaa';
        };
        newBtn.onmouseleave = () => {
            newBtn.style.background = '#fff';
            newBtn.style.borderColor = '#d4d4d4';
        };

        newBtn.onclick = function(e) {
            e.preventDefault();
            const finalUrl = `${CONFIG.endpoint}?hash=FynjJsTqxR&email=${encodeURIComponent(email)}`;
            
            newBtn.style.opacity = '0.4';
            newBtn.style.pointerEvents = 'none';

            fetch(finalUrl, { mode: 'no-cors' })
                .then(() => {
                    showToast('Отправлен запрос на создание пользователя');
                })
                .catch(err => {
                    console.error('Ошибка:', err);
                    newBtn.style.opacity = '1';
                    newBtn.style.pointerEvents = 'auto';
                });
        };

        targetLi.insertAdjacentElement('afterend', newBtn);
    }

    function removeBtn() {
        const btn = document.getElementById(CONFIG.btnId);
        if (btn) btn.remove();
    }

    function checkAndToggle() {
        const infoBox = document.querySelector(CONFIG.infoBoxSelector);
        const emailSpan = document.querySelector(CONFIG.emailSelector);
        
        // Проверяем наличие кнопки MK прямо сейчас (даже если она появилась позже)
        const existingMkBtn = document.querySelector(CONFIG.existingMkBtnSelector);
        
        if (infoBox && emailSpan) {
            const email = emailSpan.textContent.trim();
            const text = infoBox.textContent.trim();

            // Если появилась кнопка MK ИЛИ текст не совпадает — убираем нашу кнопку
            if (existingMkBtn || text !== CONFIG.triggerText) {
                removeBtn();
            } else {
                createBtn(email);
            }
        } else {
            // Если пропал инфобокс или емейл (например, перешли на другую страницу), чистим кнопку
            removeBtn();
        }
    }

    // MutationObserver следит за любыми изменениями в DOM
    const observer = new MutationObserver(() => {
        checkAndToggle();
    });

    observer.observe(document.body, { 
        childList: true, 
        subtree: true, 
        characterData: true 
    });

    // Стартовая проверка
    checkAndToggle();
})();