$(function() {
    function isStreamListPage() {
        const href = window.location.href;
        const path = (href.split(/[?#]/)[0] || '').replace(/\/+$/, '');
        return (
            /\/teach\/control$/.test(path) ||
            /\/teach\/control\/stream$/.test(path) ||
            /\/teach\/control\/stream\/index$/.test(path)
        );
    }

    function isModulesPage() {
        const href = window.location.href;
        return (
            href.includes('/teach/control/stream/view/id/') ||
            href.includes('/teach/control/stream/view?id=')
        );
    }

    function isNonAdmin() {
        return !window.userInfo || !window.userInfo.isAdmin;
    }

    function pluralLessons(n) {
        const mod10 = n % 10;
        const mod100 = n % 100;
        if (mod10 === 1 && mod100 !== 11) return n + ' урок';
        if (mod10 >= 2 && mod10 <= 4 && (mod100 < 12 || mod100 > 14)) return n + ' урока';
        return n + ' уроков';
    }

    function parseModuleMeta(link) {
        const titleEl = link.querySelector('.stream-title');
        const descEl = Array.from(link.children).find(
            (el) =>
                el.tagName === 'DIV' &&
                !el.classList.contains('module-card__cta') &&
                !el.classList.contains('module-card__illust') &&
                !el.classList.contains('module-card__desc') &&
                !el.classList.contains('module-card__lessons')
        );

        let sourceTitle = '';
        if (titleEl) {
            sourceTitle = titleEl.textContent.trim().replace(/\s+/g, ' ');
        } else {
            const textBits = [];
            Array.from(link.childNodes).forEach((node) => {
                if (node.nodeType === Node.TEXT_NODE) {
                    const t = node.textContent.trim();
                    if (t) textBits.push(t);
                }
            });
            sourceTitle = textBits.join(' ').replace(/\s+/g, ' ').trim();
            if (!sourceTitle && descEl) {
                sourceTitle = descEl.textContent.trim().replace(/\s+/g, ' ');
            }
        }

        const rawDesc = descEl ? descEl.textContent.trim().replace(/\s+/g, ' ') : '';

        // GC: .stream-title = "МОДУЛЬ N. Тема…", div = "N урока." / "нет уроков"
        const titleModuleMatch = sourceTitle.match(/^модуль\s*(\d+)\s*[.:]?\s*(.*)$/i);
        let moduleLabel = sourceTitle;
        let subtitle = '';

        if (titleModuleMatch) {
            moduleLabel = 'Модуль ' + titleModuleMatch[1];
            subtitle = (titleModuleMatch[2] || '').trim();
        }

        const lessonsMatch = rawDesc.match(/(\d+)\s*уро/i);
        const noLessons = /нет\s*уро/i.test(rawDesc);
        const lessonsCount = lessonsMatch ? parseInt(lessonsMatch[1], 10) : null;

        // тема из div — только если это не счётчик уроков и не копия заголовка
        if (!subtitle && rawDesc && !lessonsMatch && !noLessons) {
            const sameAsTitle =
                rawDesc.toLowerCase() === moduleLabel.toLowerCase() ||
                rawDesc.toLowerCase() === sourceTitle.toLowerCase();
            if (!sameAsTitle) {
                subtitle = rawDesc;
            }
        }

        if (
            subtitle &&
            (subtitle.toLowerCase() === moduleLabel.toLowerCase() ||
                subtitle.toLowerCase() === sourceTitle.toLowerCase())
        ) {
            subtitle = '';
        }

        return {
            moduleLabel,
            moduleNumber: titleModuleMatch ? titleModuleMatch[1] : null,
            rawTitle: sourceTitle,
            subtitle,
            lessonsLabel: lessonsCount != null ? pluralLessons(lessonsCount) : null,
            noLessons,
            titleEl,
            descEl,
        };
    }

    function resolveModuleImage(meta, trainingId) {
        const cfg = window.kbclinicModuleImages || (typeof kbclinicModuleImages !== 'undefined' ? kbclinicModuleImages : null);
        if (!cfg) return '';

        const label = (meta.moduleLabel || '').trim();
        const rawTitle = (meta.rawTitle || label).trim();
        const num = meta.moduleNumber != null ? String(meta.moduleNumber) : '';
        const id = trainingId ? String(trainingId) : '';

        function pickFromObject(obj) {
            if (!obj || typeof obj !== 'object') return '';
            if (id && obj[id]) return obj[id];
            if (id && obj['id:' + id]) return obj['id:' + id];
            if (label && obj[label]) return obj[label];
            if (rawTitle && obj[rawTitle]) return obj[rawTitle];
            // case-insensitive title match
            const keys = Object.keys(obj);
            const lowerLabel = label.toLowerCase();
            const lowerRaw = rawTitle.toLowerCase();
            for (let i = 0; i < keys.length; i++) {
                const k = keys[i];
                if (k === 'default') continue;
                const kl = k.toLowerCase();
                if (kl === lowerLabel || kl === lowerRaw) return obj[k];
            }
            if (num && obj['Модуль ' + num]) return obj['Модуль ' + num];
            if (num && obj[num]) return obj[num];
            return obj.default || '';
        }

        if (Array.isArray(cfg)) {
            if (id) {
                const byId = cfg.find((item) => item && String(item.id) === id);
                if (byId && byId.image) return byId.image;
            }
            const byTitle = cfg.find((item) => {
                if (!item || !item.title) return false;
                const t = String(item.title).trim().toLowerCase();
                return t === label.toLowerCase() || t === rawTitle.toLowerCase();
            });
            if (byTitle && byTitle.image) return byTitle.image;
            if (num) {
                const byNum = cfg.find((item) => item && String(item.title).replace(/\D/g, '') === num);
                if (byNum && byNum.image) return byNum.image;
            }
            const fallback = cfg.find((item) => item && (item.title === 'default' || item.default));
            return (fallback && (fallback.image || fallback.default)) || '';
        }

        return pickFromObject(cfg);
    }

    const MODULE_CARD_BG = 'rgba(50, 172, 245, 0.1)';
    const MODULE_CARD_SHADOW =
        '8px 8px 12px rgba(144, 138, 163, 0.1), -8px -8px 12px rgba(144, 138, 163, 0.1)';

    function bindModuleCardHover(link) {
        if (link.dataset.kbHoverBound) return;
        link.dataset.kbHoverBound = '1';

        const td = link.closest('td');
        if (td) {
            td.style.background = 'transparent';
            td.style.backgroundImage = 'none';
            td.style.overflow = 'visible';
            td.style.borderRadius = '0';
        }

        link.style.width = '100%';
        link.style.borderRadius = '24px';
        link.style.background = MODULE_CARD_BG;
        link.style.boxSizing = 'border-box';
        link.style.overflow = 'visible';
        link.style.transition = 'transform 0.15s ease, box-shadow 0.15s ease';

        function setLift(on) {
            link.style.transform = on ? 'translateY(-2px)' : '';
            link.style.boxShadow = on ? MODULE_CARD_SHADOW : '';
        }

        link.addEventListener('mouseenter', () => setLift(true));
        link.addEventListener('mouseleave', () => setLift(false));
        link.addEventListener('focus', () => setLift(true));
        link.addEventListener('blur', () => setLift(false));
    }

    function enhanceModuleCard(link) {
        if (link.classList.contains('course-card')) return;

        if (!link.classList.contains('module-card')) {
        link.classList.add('module-card');
        const row = link.closest('tr');
        const td = link.closest('td');
        if (row) row.classList.add('module-card-row');
        if (td) td.classList.add('module-card-td');

        const meta = parseModuleMeta(link);
        const trainingId = row ? row.getAttribute('data-training-id') : '';

        if (!link.querySelector('.module-card__lessons') && meta.lessonsLabel) {
            const badge = document.createElement('span');
            badge.className = 'module-card__lessons';
            badge.textContent = meta.lessonsLabel;
            link.insertBefore(badge, link.firstChild);
        }

        let titleEl = meta.titleEl;
        if (!titleEl) {
            titleEl = document.createElement('span');
            titleEl.className = 'stream-title';
            Array.from(link.childNodes).forEach((node) => {
                if (node.nodeType === Node.TEXT_NODE && node.textContent.trim()) {
                    node.textContent = '';
                }
            });
            link.appendChild(titleEl);
        }
        titleEl.textContent = meta.moduleLabel;

        let descEl = meta.descEl;
        if (meta.subtitle) {
            if (!descEl) {
                descEl = document.createElement('div');
                link.appendChild(descEl);
            }
            descEl.classList.add('module-card__desc');
            descEl.textContent = meta.subtitle;
        } else if (descEl) {
            // GC-div был счётчиком уроков — не показываем как описание
            descEl.remove();
        }

        const imageUrl = resolveModuleImage(meta, trainingId);
        if (imageUrl && !link.querySelector('.module-card__illust')) {
            const illust = document.createElement('span');
            illust.className = 'module-card__illust';
            illust.setAttribute('aria-hidden', 'true');
            illust.style.backgroundImage = 'url("' + imageUrl.replace(/"/g, '\\"') + '")';
            link.appendChild(illust);
        }

        if (!link.querySelector('.module-card__cta')) {
            const cta = document.createElement('span');
            cta.className = 'module-card__cta';
            cta.innerHTML =
                '<span class="module-card__cta-text">Перейти</span>' +
                '<span class="module-card__cta-arrow" aria-hidden="true"></span>';
            link.appendChild(cta);
        }
        }

        bindModuleCardHover(link);
    }

    function resolveModuleQuickLinks(assets) {
        if (assets && assets.quickLinks) return assets.quickLinks;

        const cfg =
            window.kbclinicModuleQuickLinks ||
            (typeof kbclinicModuleQuickLinks !== 'undefined' ? kbclinicModuleQuickLinks : null);

        return Array.isArray(cfg) ? cfg : [];
    }

    function setMultilineLabel(el, label) {
        el.textContent = '';
        String(label || '')
            .split('\n')
            .forEach((part, index) => {
                if (index > 0) el.appendChild(document.createElement('br'));
                el.appendChild(document.createTextNode(part));
            });
    }

    function buildQuickLinkCard(link) {
        const card = document.createElement('a');
        card.className = 'kb-quick-link kb-quick-link--' + (link.variant || 'outline-green');
        card.href = link.href || '#';

        if (link.target) card.target = link.target;
        if (/^https?:/i.test(card.href)) card.rel = 'noopener';

        const icon = document.createElement('span');
        icon.className = 'kb-quick-link__icon';
        icon.setAttribute('aria-hidden', 'true');
        const mark = document.createElement('span');
        mark.className = 'kb-quick-link__icon-mark';
        mark.textContent = '/';
        icon.appendChild(mark);

        const label = document.createElement('span');
        label.className = 'kb-quick-link__label';
        setMultilineLabel(label, link.label);

        const arrow = document.createElement('span');
        arrow.className = 'kb-quick-link__arrow';
        arrow.setAttribute('aria-hidden', 'true');

        card.append(icon, label, arrow);
        return card;
    }

    function buildModulesIntro(pageTitleEl, assets) {
        if (document.querySelector('.kb-modules-intro')) return;

        const trainingRoot =
            document.querySelector('.xdget-root .xdget-block.xdget-training.xdget-common-container') ||
            document.querySelector('.xdget-block.xdget-training');
        if (!trainingRoot) return;

        const intro = document.createElement('div');
        intro.className = 'kb-modules-intro';

        const quickLinksWrap = document.createElement('div');
        quickLinksWrap.className = 'kb-modules-quick-links';

        const links = resolveModuleQuickLinks(assets);
        links.forEach((link) => {
            quickLinksWrap.appendChild(buildQuickLinkCard(link));
        });
        if (links.length) {
            intro.appendChild(quickLinksWrap);
        }

        let title = pageTitleEl;
        if (title) {
            title.textContent = 'Основная программа обучения   —–—————';
            title.classList.add('kb-modules-title');
            intro.appendChild(title);
        } else {
            title = document.createElement('h1');
            title.className = 'kb-modules-title';
            title.textContent = 'Основная программа обучения   —–—————';
            intro.appendChild(title);
        }

        trainingRoot.insertBefore(intro, trainingRoot.firstChild);

        const pageHeader = document.querySelector('.page-header');
        if (pageHeader && !pageHeader.querySelector('h1, h2, h3')) {
            pageHeader.style.display = 'none';
        }
    }

    function buildProgressCard() {
        const card = document.createElement('div');
        card.className = 'kb-course-card kb-course-card--progress';
        card.innerHTML =
            '<p class="kb-course-card__name"></p>' +
            '<p class="kb-course-card__hint">Ваш прогресс на курсе</p>' +
            '<div class="kb-course-card__stats">' +
            '<span class="kb-course-card__stat kb-course-card__stat--done">Выполнено: 0 заданий</span>' +
            '<span class="kb-course-card__stat kb-course-card__stat--left">Осталось: 0 заданий</span>' +
            '</div>' +
            '<div class="kb-course-card__ring" style="--kb-progress:0">' +
            '<span class="kb-course-card__ring-value">0%</span>' +
            '</div>';
        return card;
    }

    function buildCareCard(cfg) {
        const curators = cfg.curators || [
            {
                role: 'Куратор',
                name: 'Бойко Валерия',
                about: 'Акушер-гинеколог, стаж 5 лет',
                photo: cfg.curatorPhoto || '',
            },
            {
                role: 'Куратор',
                name: 'Бойко Валерия',
                about: 'Акушер-гинеколог, стаж 5 лет',
                photo: cfg.curatorPhoto || '',
            },
        ];
        const card = document.createElement('div');
        card.className = 'kb-course-card kb-course-card--care';

        const list = curators
            .map((c) => {
                const photoStyle = c.photo
                    ? ' style="background-image:url(\'' + c.photo.replace(/'/g, "\\'") + '\')"'
                    : '';
                return (
                    '<div class="kb-care-person">' +
                    '<span class="kb-care-person__photo"' +
                    photoStyle +
                    ' aria-hidden="true"></span>' +
                    '<div class="kb-care-person__meta">' +
                    '<span class="kb-care-person__role">' +
                    (c.role || 'Куратор') +
                    '</span>' +
                    '<span class="kb-care-person__name">' +
                    (c.name || '') +
                    '</span>' +
                    '<span class="kb-care-person__about">' +
                    (c.about || '') +
                    '</span>' +
                    '</div></div>'
                );
            })
            .join('');

        card.innerHTML =
            '<p class="kb-course-card__care-title">Служба заботы</p>' +
            '<div class="kb-care-panel kb-care-panel--people">' +
            list +
            '</div>' +
            '<div class="kb-care-panel kb-care-panel--support">' +
            '<p class="kb-care-hours">Пн-Вс: 10:00 - 18:00 Мск</p>' +
            '<p class="kb-care-note">Время ответа технической поддержки 24 часа с момента обращения. Не переживайте, мы обязательно вам поможем!</p>' +
            '<a class="kb-care-cta" href="">Написать в поддержку</a>' +
            '</div>';

        return card;
    }

    function initModulesPageDesign() {
        if (!isModulesPage() || !isNonAdmin()) return;
        // Страница уроков (.lesson-list) — main-lesson-page.js; progress там не нужен
        if (document.querySelector('.lesson-list')) return;
        if (document.body.classList.contains('kbclinic-modules-page')) return;

        document.body.classList.add('kbclinic-modules-page');

        document.querySelectorAll('.bonus-banner, a.bonus-banner').forEach((el) => {
            const wrap = el.closest('a.banner') || el;
            wrap.remove();
        });

        document.querySelectorAll('.breadcrumbs, .empty-breadcrumbs').forEach((el) => {
            el.style.display = 'none';
        });

        const root = document.querySelector('.xdget-root');
        if (!root) return;

        const assets = Object.assign(
            {
                curatorPhoto: '',
                supportHref: '',
                curators: null,
                quickLinks: null,
            },
            window.kbclinicModulesAssets || {}
        );

        const pageTitle = document.querySelector('.page-header > h1');
        buildModulesIntro(pageTitle, assets);

        let rightPanel = root.querySelector(':scope > .right-panel');
        if (!rightPanel) {
            rightPanel = document.createElement('div');
            rightPanel.className = 'right-panel';
            root.appendChild(rightPanel);
        }

        rightPanel.innerHTML = '';
        rightPanel.appendChild(buildProgressCard());
        rightPanel.appendChild(
            buildCareCard({
                curatorPhoto: assets.curatorPhoto,
                supportHref: assets.supportHref,
                curators: assets.curators,
            })
        );

        document
            .querySelectorAll('.stream-table tr.training-row td > a')
            .forEach(enhanceModuleCard);
    }

    if (isStreamListPage()) {
        const lessonsList = $('.stream-table tbody tr td a');
        const featuredLink = document.querySelector(
            '.xdget-root .row > .col-md-12 .stream-table tr.training-row td > a'
        );
        lessonsList.each(function () {
            if (this === featuredLink || this.classList.contains('course-card') || this.classList.contains('stream-card')) return;
            if (this.closest('.stream-table')) return;

            const description = $(this).find('div');
            if (description.text().trim().length > 0) {
                description.find('b').remove();
                const textDescription = description
                    .text()
                    .trim()
                    .replace(/\n/g, '')
                    .replace('\t', '');
                if (textDescription.length == 0) {
                    description.remove();
                } else if (textDescription.length > 30) {
                    description.text(textDescription.substring(0, 27) + '...');
                }
            }
            const textTitle = $(this)
                .find('.stream-title')
                .text()
                .trim()
                .replace(/\n/g, '')
                .replace('\t', '');
            if (textTitle.length > 40) {
                $(this)
                    .find('.stream-title')
                    .text(textTitle.substring(0, 37) + '...');
            } else {
                $(this).find('.stream-title').text(textTitle);
            }
        });

        document.querySelectorAll('.bonus-banner').forEach((el) => el.remove());
    }

    // после main-lesson-page.js (он грузится следом и вешает свой ready)
    setTimeout(initModulesPageDesign, 0);
    setTimeout(initModulesPageDesign, 100);
});
