(function() {
    const CONFIG = {
        segmentId: "35113834",
        btnClass: 'menu-item-teacher-cabinet'
    };

    async function toggleTeacherButton() {
        const btn = document.querySelector(`.${CONFIG.btnClass}`);
        if (!btn) return;

        const userId = window.accountUserId;
        // Кэш привязан к версии, чтобы избежать старых ошибок
        const cacheKey = `teacher_access_vFinal_v2_${userId}`; 
        let isAllowed = sessionStorage.getItem(cacheKey);

        if (isAllowed === null) {
            try {
                const response = await fetch(`https://online.systematika.org/chtm/checksegment?userId=${userId}&segmentId=${CONFIG.segmentId}`);
                const data = await response.json();
                const body = typeof data.body === 'string' ? JSON.parse(data.body) : data.body;
                isAllowed = (body && body.result === true) ? 'true' : 'false';
                sessionStorage.setItem(cacheKey, isAllowed);
            } catch (e) { return; }
        }

        if (isAllowed === 'true') {
            // Если доступ разрешен — проявляем
            btn.style.setProperty('display', 'block', 'important');
            btn.style.setProperty('order', '0', 'important');
        } else {
            // Если доступ ЗАПРЕЩЕН — удаляем кнопку из меню совсем
            btn.remove();
            console.log("Кабинет учителя скрыт: пользователь не в сегменте.");
        }
    }

    const initTimer = setInterval(() => {
        if (document.querySelector(`.${CONFIG.btnClass}`)) {
            toggleTeacherButton();
            clearInterval(initTimer);
        }
    }, 500);
})();