$(function() {
    const href = window.location.href;
    const path = (href.split(/[?#]/)[0] || '').replace(/\/+$/, '');
    const isStreamListPage =
        /\/teach\/control$/.test(path) ||
        /\/teach\/control\/stream$/.test(path) ||
        /\/teach\/control\/stream\/index$/.test(path);
    const isListOrStream =
        isStreamListPage ||
        /\/teach\/control\/stream\//.test(path) ||
        href.includes('/teach/control/lesson/view');

    const shouldShowHeader = isListOrStream;

    if (shouldShowHeader) {
        $('body').prepend(`<div class='training_header'>
        <div class='container'></div>
        </div>`);
        $('.training_header .container').append($('.gc-account-logo'));
    }
    if ($('body').hasClass('chatium_body')) {
        const logoUrl =
            (window.kbclinicUiAssets && window.kbclinicUiAssets.loginLogoWhite) ||
            'https://fs.getcourse.ru/fileservice/file/download/a/951813/sc/484/h/3de1b0dc44e362530860d62b13311045.png';
        const $logo = $('<div class="logo gc-account-logo"></div>');
        const $link = $('<a href="/" class="logo-link" aria-label="КБклиник"></a>');
        $link.css({
            backgroundImage: 'url("' + logoUrl + '")',
            backgroundPosition: 'center',
            backgroundSize: 'contain',
            backgroundRepeat: 'no-repeat',
        });
        $logo.append($link);
        $('.training_header .container').prepend($logo);
    }

    const isLessonViewPage =
        href.includes('/teach/control/lesson/view') ||
        href.includes('/pl/teach/control/lesson/view');

    function normalizeText(value) {
        return String(value || '')
            .replace(/\s+/g, ' ')
            .trim();
    }

    function fillHeroTitles(title, description) {
        const main = document.querySelector('.training_header__title-main');
        const top = document.querySelector('.training_header__title-top');
        if (main && title) main.textContent = title;
        if (top && description) top.textContent = description;
    }

    function parseCourseMetaFromHtml(html) {
        const $dom = $('<div></div>').append($.parseHTML(html, document, false));
        return {
            title: normalizeText($dom.find('.page-header h1').first().text()),
            description: normalizeText(
                $dom.find('div.training-hidden-data').attr('data-description')
            ),
        };
    }

    function isLessonsListPage() {
        return !!document.querySelector('.lesson-list');
    }

    function getParentCourseBreadcrumbLink() {
        const crumbs = document.querySelector('.breadcrumbs, .breadcrumbs.kb-module-crumbs');
        if (!crumbs) return null;
        const links = crumbs.querySelectorAll('a');
        if (links[1] && links[1].getAttribute('href')) return links[1];
        return crumbs.querySelector('a[href*="/stream/view"]');
    }

    function fillHeroFromParentCourse() {
        const link = getParentCourseBreadcrumbLink();
        if (!link) return;

        const linkTitle = normalizeText(link.textContent);
        if (linkTitle) fillHeroTitles(linkTitle, '');

        const courseUrl = link.getAttribute('href');
        if (!courseUrl) return;

        const cacheKey = 'kbclinic_header_course:' + courseUrl;
        try {
            const cached = sessionStorage.getItem(cacheKey);
            if (cached) {
                const meta = JSON.parse(cached);
                fillHeroTitles(meta.title || linkTitle, meta.description || '');
                return;
            }
        } catch (e) {
            /* ignore */
        }

        if (fillHeroFromParentCourse._loading === courseUrl) return;
        fillHeroFromParentCourse._loading = courseUrl;

        $.ajax({
            method: 'GET',
            url: courseUrl,
            dataType: 'html',
        })
            .done(function (html) {
                const meta = parseCourseMetaFromHtml(html);
                const title = meta.title || linkTitle;
                const description = meta.description || '';
                try {
                    sessionStorage.setItem(
                        cacheKey,
                        JSON.stringify({ title: title, description: description })
                    );
                } catch (e) {
                    /* ignore */
                }
                fillHeroTitles(title, description);
            })
            .always(function () {
                if (fillHeroFromParentCourse._loading === courseUrl) {
                    fillHeroFromParentCourse._loading = null;
                }
            });
    }

    function fillHeroFromCurrentPage() {
        fillHeroTitles(
            normalizeText($('.page-header h1').first().text()),
            normalizeText($('div.training-hidden-data').attr('data-description'))
        );
    }

    if (shouldShowHeader && !isStreamListPage && !isLessonViewPage && $('.training_header__hero').length === 0) {
        const hero = $(`
            <div class="training_header__hero">
                <div class="training_header__doctor">
                    <div class="training_header__doctor-name">
                        <span>Алексей Жданюк</span>
                        <span>K.M.H – врач травматолог ортопед,</span>
						<span>владелиц сети клиник</span>
                    </div>
                    <img
                        class="training_header__doctor-image"
                        src="https://fs.getcourse.ru/fileservice/file/download/a/951813/sc/403/h/baf58769c2dcdce6331ec6b6574d9fcf.png"
                        alt="Доктор Алексей Жданюк"
                    >
                </div>
                <div class="training_header__copy">
                    <div class="training_header__brand"></div>
                    <div class="training_header__title">
                        <span class="training_header__title-main"></span>
                        <span class="training_header__title-top"></span>
                    </div>
                </div>
            </div>
        `);

        $('.training_header .container').append(hero);

        const logo = $('.training_header .container > .gc-account-logo').first();
        if (logo.length) {
            $('.training_header__brand').append(logo);
        }

        if (isLessonsListPage()) {
            fillHeroFromParentCourse();
        } else {
            fillHeroFromCurrentPage();
        }
    }

    window.kbclinicFillLessonsHeader = fillHeroFromParentCourse;

    // breadcrumbs / lesson-list могут появиться чуть позже
    if (shouldShowHeader && !isStreamListPage && !isLessonViewPage) {
        setTimeout(function () {
            if (!isLessonsListPage()) return;
            if (!$('.training_header__title-top').text().trim()) {
                fillHeroFromParentCourse();
            }
        }, 300);
    }
});
