MediaWiki:Common.js: відмінності між версіями

Матеріал з Київський національний лінгвістичний університет
Перейти до навігації Перейти до пошуку
Немає опису редагування
Мітка: Скасовано
Немає опису редагування
 
(Не показані 52 проміжні версії цього користувача)
Рядок 1: Рядок 1:
/* ── Заголовок сторінки ── */
// Виправляємо viewport
#firstHeading {
(function() {
     font-size: clamp(28px, 4vw, 48px);
    var viewport = document.querySelector('meta[name="viewport"]');
}
    if (viewport) {
        viewport.setAttribute('content', 'width=device-width, initial-scale=1.0, maximum-scale=5.0, viewport-fit=cover');
    } else {
        var meta = document.createElement('meta');
        meta.name = 'viewport';
        meta.content = 'width=device-width, initial-scale=1.0, maximum-scale=5.0, viewport-fit=cover';
        document.head.appendChild(meta);
    }
})();
 
$(function() {
    $('.category-card').each(function() {
        var $card = $(this);
        var href = $card.attr('data-href');
 
        if (href) {
            $card.css('cursor', 'pointer');
 
            $card.on('click', function(e) {
                if ($(e.target).closest('a').length === 0) {
                    window.location.href = href;
                }
            });
 
            $card.hover(
                function() { $card.addClass('card-hover'); },
                function() { $card.removeClass('card-hover'); }
            );
        }
    });
});
 
/* ══════════════════════════════════════════════
  МОБІЛЬНА ШАПКА
══════════════════════════════════════════════ */
 
mw.hook('wikipage.content').add(function() {
 
    var overlay = document.createElement('div');
    overlay.className = 'mobile-menu-overlay';
    document.body.appendChild(overlay);
 
    var topbar = document.createElement('div');
    topbar.className = 'mobile-topbar';
 
    var wikiLogo = document.querySelector('#p-logo img, .mw-wiki-logo img, img.mw-logo-icon, #p-logo a, .mw-logo img');
    var logoSrc = '';
    if (wikiLogo && wikiLogo.tagName === 'IMG') {
        logoSrc = wikiLogo.src;
    } else if (wikiLogo && wikiLogo.tagName === 'A') {
        var bgStyle = window.getComputedStyle(wikiLogo).backgroundImage;
        if (bgStyle && bgStyle !== 'none') {
            var bgMatch = bgStyle.match(/url\(["']?([^"')]+)["']?\)/);
            if (bgMatch) logoSrc = bgMatch[1];
        }
    }
    var mainPageUrl = mw.config.get('wgArticlePath').replace('$1', encodeURIComponent('Головна_сторінка'));
    var siteName = mw.config.get('wgSiteName') || 'Вікі університету';
    var shortName = siteName.replace('Вікі ', '').split(' ').slice(0, 3).join(' ');
    var userName = mw.config.get('wgUserName');
     var isLoggedIn = !!userName;
    var articlePath = mw.config.get('wgArticlePath');
 
    var logoHtml = logoSrc
        ? '<img src="' + logoSrc + '" alt="Логотип" style="max-width:32px!important;width:32px;height:32px;">'
        : '<span style="display:flex;align-items:center;justify-content:center;width:32px;height:32px;background:#003d82;color:#fff;font-weight:700;font-size:16px;border-radius:8px;flex-shrink:0;">' + (siteName.charAt(0) || 'В') + '</span>';
 
    var userInitial = isLoggedIn ? (userName.charAt(0).toUpperCase()) : '';
    var userAvatarHtml = isLoggedIn
        ? '<span class="topbar-user-avatar" aria-label="' + mw.html.escape(userName) + '">' + mw.html.escape(userInitial) + '</span>'
        : '<a class="topbar-login-btn" href="' + articlePath.replace('$1', 'Special:UserLogin') + '" aria-label="Увійти"><svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"/><circle cx="12" cy="7" r="4"/></svg></a>';
 
    var dropdownHtml = isLoggedIn
        ? '<div class="topbar-user-dropdown" id="topbar-user-dropdown">' +
            '<div class="topbar-dropdown-header">' +
                '<span class="topbar-dropdown-avatar">' + mw.html.escape(userInitial) + '</span>' +
                '<span class="topbar-dropdown-name">' + mw.html.escape(userName) + '</span>' +
            '</div>' +
            '<div class="topbar-dropdown-divider"></div>' +
            '<a class="topbar-dropdown-item" href="' + articlePath.replace('$1', 'Користувач:' + encodeURIComponent(userName)) + '">' +
                '<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"/><circle cx="12" cy="7" r="4"/></svg>' +
                'Профіль' +
            '</a>' +
            '<a class="topbar-dropdown-item" href="' + articlePath.replace('$1', 'Special:Preferences') + '">' +
                '<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="3"/><path d="M19.07 4.93a10 10 0 0 1 0 14.14M4.93 4.93a10 10 0 0 0 0 14.14"/></svg>' +
                'Налаштування' +
            '</a>' +
            '<div class="topbar-dropdown-divider"></div>' +
            '<a class="topbar-dropdown-item topbar-dropdown-logout" href="' + mw.config.get('wgScript') + '?title=Special:UserLogout&returnto=Головна_сторінка">' +
                '<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4"/><polyline points="16 17 21 12 16 7"/><line x1="21" y1="12" x2="9" y2="12"/></svg>' +
                'Вийти' +
            '</a>' +
        '</div>'
        : '';
 
    topbar.innerHTML =
        '<button class="topbar-menu-btn" id="topbar-menu-btn" aria-label="Меню">' +
            '<span class="topbar-hamburger"><span></span><span></span><span></span></span>' +
        '</button>' +
        '<a class="mobile-topbar-logo" href="' + mainPageUrl + '" aria-label="На головну">' +
            logoHtml +
            '<span class="mobile-topbar-logo-text">' + mw.html.escape(shortName) + '</span>' +
        '</a>' +
        '<div class="mobile-topbar-search" id="mobile-topbar-search-slot"></div>' +
        '<div class="topbar-user-wrap" id="topbar-user-wrap">' +
            userAvatarHtml +
            dropdownHtml +
        '</div>';
 
    document.body.insertBefore(topbar, document.body.firstChild);
 
    var nativeSearch = document.getElementById('p-search');
    if (!nativeSearch) nativeSearch = document.querySelector('#mw-head #p-search');


/* ── Бокове меню ── */
    var searchSlot = document.getElementById('mobile-topbar-search-slot');
#mw-panel {
    font-size: clamp(14px, 1.2vw, 18px);
}


/* ── Прибираємо обмеження Vector ── */
    if (nativeSearch && searchSlot) {
body.skin-vector-2022 .mw-page-container-inner,
        var searchOriginalParent = nativeSearch.parentNode;
body.skin-vector .mw-content-container,
        var searchOriginalNextSibling = nativeSearch.nextSibling;
body.skin-vector .vector-body,
body.skin-vector #bodyContent {
    max-width: none !important;
    padding-left: 0 !important;
    padding-right: 0 !important;
}


body.skin-vector-2022 .mw-body,
        function moveSearchToTopbar() {
body.skin-vector-2022 .mw-body-content {
            if (!searchSlot.contains(nativeSearch)) {
    max-width: none !important;
                searchSlot.appendChild(nativeSearch);
    margin: 0 !important;
            }
}
        }


/* ════════════════════════════════════
        function moveSearchBack() {
  ПРИВІТАННЯ + СТАТИСТИКА
            if (searchSlot.contains(nativeSearch)) {
═══════════════════════════════════════ */
                if (searchOriginalNextSibling && searchOriginalParent.contains(searchOriginalNextSibling)) {
.welcome-wrapper {
                    searchOriginalParent.insertBefore(nativeSearch, searchOriginalNextSibling);
    display: flex;
                } else {
    align-items: center;
                    searchOriginalParent.appendChild(nativeSearch);
    justify-content: space-between;
                }
    gap: 40px;
            }
    padding: 40px 5vw 40px;
        }
    box-sizing: border-box;
    width: 100%;
}


.welcome-text {
        if (window.innerWidth <= 1100) {
    flex: 1;
            moveSearchToTopbar();
    text-align: center;
        }
    /* Зміщуємо центр тексту компенсуючи ширину панелі статистики */
    transform: translateX(-80px);
}


.welcome-subtitle {
        var resizeTimer;
    font-family: system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
        window.addEventListener('resize', function() {
    font-size: 1.45rem;
            clearTimeout(resizeTimer);
    font-weight: 400;
            resizeTimer = setTimeout(function() {
    color: #444;
                if (window.innerWidth <= 1100) {
    letter-spacing: 0.6px;
                    moveSearchToTopbar();
    margin-bottom: 10px;
                } else {
     opacity: 0.92;
                    moveSearchBack();
}
                }
            }, 100);
        });
     }


.welcome-title {
    var userWrap = topbar.querySelector('#topbar-user-wrap');
     font-family: system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
     var userDropdown = topbar.querySelector('#topbar-user-dropdown');
    font-size: 2.45rem;
    if (userWrap && userDropdown) {
    font-weight: 700;
        userWrap.addEventListener('click', function(e) {
    line-height: 1.18;
            e.stopPropagation();
    color: #003d82;
            var isOpen = userDropdown.classList.contains('open');
    letter-spacing: -0.3px;
            userDropdown.classList.toggle('open', !isOpen);
    margin: 0;
        });
}
        document.addEventListener('click', function() {
            userDropdown.classList.remove('open');
        });
    }


/* ── Панель статистики (справа від привітання) ── */
    function openMenu() {
.stats-panel {
        document.body.classList.add('mobile-nav-open');
    width: 260px;
        overlay.classList.add('open');
    flex-shrink: 0;
        var menuBtn = topbar.querySelector('#topbar-menu-btn');
    background: white;
        if (menuBtn) menuBtn.classList.add('active');
    border-radius: 16px;
     }
    border: 1px solid rgba(0,61,130,0.08);
    box-shadow: 0 6px 24px rgba(0,0,0,0.07);
     overflow: hidden;
}


.stats-panel-header {
    function closeMenu() {
    background: rgba(210, 230, 255, 0.35);
        document.body.classList.remove('mobile-nav-open');
    color: #003d82;
        overlay.classList.remove('open');
    font-family: system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
        var menuBtn = topbar.querySelector('#topbar-menu-btn');
    font-size: 1rem;
        if (menuBtn) menuBtn.classList.remove('active');
    font-weight: 700;
    }
    padding: 12px 18px;
    border-bottom: 1px solid rgba(0,61,130,0.1);
}


.stats-panel-list {
    var topbarMenuBtn = topbar.querySelector('#topbar-menu-btn');
    padding: 4px 0;
    if (topbarMenuBtn) {
}
        topbarMenuBtn.addEventListener('click', function(e) {
            e.stopPropagation();
            if (document.body.classList.contains('mobile-nav-open')) {
                closeMenu();
            } else {
                openMenu();
            }
        });
    }


.stats-panel-item {
    overlay.addEventListener('click', closeMenu);
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 10px 18px;
    border-bottom: 1px solid rgba(0,61,130,0.05);
    transition: background 0.2s;
}


.stats-panel-item:last-child {
    document.addEventListener('keydown', function(e) {
    border-bottom: none;
        if (e.key === 'Escape') closeMenu();
}
    });


.stats-panel-item:hover {
    window.addEventListener('resize', function() {
    background: rgba(210, 230, 255, 0.2);
        if (window.innerWidth > 1100) closeMenu();
}
    });
});


.stats-panel-label {
    font-family: system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
    font-size: 14px;
    color: #555;
}


.stats-panel-number {
/* ══════════════════════════════════════════════
    font-family: system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
  МОБІЛЬНИЙ ФІК РОЗМІРУ THUMB-КАРТИНОК
     font-size: 18px;
══════════════════════════════════════════════ */
    font-weight: 800;
mw.hook('wikipage.content').add(function() {
    color: #003d82;
     function fixThumbWidths() {
}
        if (window.innerWidth > 1100) return;


/* ════════════════════════════════════
        var vw = window.innerWidth;
  ЗАГОЛОВОК КАТЕГОРІЙ
        var targetWidth = Math.min(280, Math.max(120, Math.round(vw * 0.48)));
═══════════════════════════════════════ */
.section-categories {
    font-family: system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
    font-size: 2.1rem;
    font-weight: 700;
    color: #003d82;
    text-align: center;
    margin: 30px 0 30px;
    /* Компенсуємо ширину правої колонки щоб текст був по центру сітки */
    padding: 0 calc(360px + 24px) 0 0;
    background: transparent;
    box-sizing: border-box;
}


.section-categories::after {
        document.querySelectorAll('.mw-parser-output .thumbinner').forEach(function(el) {
    content: '';
            el.style.removeProperty('width');
    display: block;
            el.style.setProperty('width', targetWidth + 'px', 'important');
    width: 90px;
            el.style.setProperty('max-width', '100%', 'important');
    height: 4px;
            el.style.setProperty('box-sizing', 'border-box', 'important');
    background: #ffd700;
        });
    margin: 14px auto 0;
    border-radius: 2px;
}


/* ════════════════════════════════════
        document.querySelectorAll('.mw-parser-output .thumbinner img').forEach(function(el) {
  ОСНОВНИЙ LAYOUT: категорії + права колонка
            el.style.setProperty('width', '100%', 'important');
═══════════════════════════════════════ */
            el.style.setProperty('max-width', '100%', 'important');
.main-content-layout {
            el.style.setProperty('height', 'auto', 'important');
    display: flex;
        });
    gap: 24px;
     }
    align-items: flex-start;
    padding: 0 5vw;
    margin: 0 0 70px;
    box-sizing: border-box;
     width: 100%;
}


/* ── Сітка карток — 3 в ряд ── */
     fixThumbWidths();
.category-grid-container {
     window.addEventListener('resize', fixThumbWidths, { passive: true });
     display: grid;
});
     grid-template-columns: repeat(3, 1fr);
    gap: 20px;
    flex: 1;
    min-width: 0;
}


/* ── Права колонка ── */
.right-column {
    width: 360px;
    min-width: 360px;
    flex-shrink: 0;
    display: flex;
    flex-direction: column;
    gap: 20px;
    align-self: flex-start;
    padding-top: 0;
}


/* ════════════════════════════════════
/* ══════════════════════════════════════════════
   КАРТКИ КАТЕГОРІЙ
   ГЛОБАЛЬНІ ПАРСЕРИ
═══════════════════════════════════════ */
══════════════════════════════════════════════ */
.category-card {
    background: white;
    border-radius: 16px;
    overflow: hidden;
    box-shadow: 0 6px 24px rgba(0,0,0,0.08);
    transition: all 0.28s cubic-bezier(0.165, 0.84, 0.44, 1);
    cursor: pointer;
    border: 1px solid rgba(0,61,130,0.08);
    height: 100%;
    display: flex;
    flex-direction: column;
}


.category-card:hover {
function extractImageName(wikitext) {
     transform: translateY(-6px);
     if (!wikitext) return null;
     box-shadow: 0 20px 40px rgba(0,61,130,0.18);
    var m = wikitext.match(/\|\s*image\s*=\s*([^\|\n\}]+)/i);
     border-color: rgba(0,61,130,0.15);
     if (m && m[1].trim()) return m[1].trim();
     m = wikitext.match(/\[\[(?:Файл|File|Зображення|Image):([^\|\]]+)/i);
    return m ? m[1].trim() : null;
}
}


.card-image {
function extractDescription(wikitext) {
     padding: 28px 0 16px;
     if (!wikitext) return '';
     flex-grow: 1;
     var text = wikitext;
    display: flex;
    align-items: center;
    justify-content: center;
    background: white;
}


.card-image img {
    var depth = 0, end = -1;
     width: 88px;
     for (var i = 0; i < text.length; i++) {
    height: 88px;
        if (text[i] === '{' && text[i + 1] === '{') { depth++; i++; }
    object-fit: contain;
        else if (text[i] === '}' && text[i + 1] === '}') {
     transition: transform 0.35s ease;
            depth--;
}
            if (depth === 0) { end = i + 2; break; }
            i++;
        }
     }
    if (end > 0) text = text.substring(end);


.category-card:hover .card-image img {
    text = text
    transform: scale(1.12);
        .replace(/\[\[(?:Файл|File|Зображення|Image):[^\]]*\]\]/gi, '')
}
        .replace(/\{\|[\s\S]*?\|\}/g, '')
        .replace(/\{\{[^}]*\}\}/g, '')
        .replace(/={2,6}[^=\n]+=+/g, '')
        .replace(/\[\[(?:[^\|\]]*\|)?([^\]]+)\]\]/g, '$1')
        .replace(/\[[^\s\]]+\s+([^\]]+)\]/g, '$1')
        .replace(/\[[^\]]+\]/g, '')
        .replace(/'{2,3}/g, '')
        .replace(/<[^>]+>/g, '')
        .replace(/^[\*#:;].*/gm, '');


.card-title {
     var lines = text.split('\n')
    font-size: 15px;
        .map(function (l) { return l.trim(); })
    font-weight: 600;
        .filter(function (l) { return l.length > 20; });
    color: #003d82;
     text-align: center;
    padding: 8px 12px 12px;
    line-height: 1.4;
    flex-grow: 0;
    background: rgba(210, 230, 255, 0.15);
    border-radius: 10px;
    margin: 0 10px 14px;
}


.card-title pre {
     if (!lines.length) return '';
     background: transparent !important;
     var result = lines[0].substring(0, 160);
     border: none !important;
     return lines[0].length > 160 ? result + '…' : result;
    box-shadow: none !important;
    padding: 0 !important;
     margin: 0 !important;
    font-family: inherit !important;
    font-size: inherit !important;
    font-weight: inherit !important;
    color: inherit !important;
    white-space: normal !important;
}
}


/* ════════════════════════════════════
/* ══════════════════════════════════════════════
   ВИПАДКОВІ СТАТТІ
   ВИПАДКОВІ СТАТТІ
═══════════════════════════════════════ */
══════════════════════════════════════════════ */
.random-articles-panel {
 
     background: white;
function loadRandomArticles() {
     border-radius: 16px;
    var list = document.getElementById('random-articles-list');
     border: 1px solid rgba(0,61,130,0.08);
     if (!list) return;
    box-shadow: 0 6px 24px rgba(0,0,0,0.07);
 
    overflow: hidden;
     list.innerHTML = '<div class="random-articles-loading">Завантаження...</div>';
    display: flex;
 
    flex-direction: column;
     var apiBase = mw.config.get('wgScriptPath') + '/api.php';
     position: relative;
    var excludedPages = [
}
        'Головна сторінка',
        'Структурні підрозділи',
        'Викладачі',
        'Історія університету',
        'Керівництво університету',
        'Факультети і кафедри',
        'Освітні програми',
        'Сертифікатні програми і курси',
        'Періодичні видання',
        'Наукові конференції',
        'Видатні випускники',
        'Історичні постаті',
        'Корпоративна культура'
     ];


    fetch(apiBase + '?action=query&list=random&rnnamespace=0&rnlimit=10&format=json')
        .then(function(r) { return r.json(); })
        .then(function(data) {
            var pages = data.query.random.filter(function(p) {
                return excludedPages.indexOf(p.title) === -1;
            }).slice(0, 3);


            var titles = pages.map(function(p) { return p.title; }).join('|');


.random-articles-header {
            return fetch(
    background: rgba(210, 230, 255, 0.35);
                apiBase +
    color: #003d82;
                '?action=query' +
    font-family: system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
                '&titles=' + encodeURIComponent(titles) +
    font-size: 1rem;
                '&prop=revisions' +
    font-weight: 700;
                '&rvprop=content' +
    padding: 14px 18px;
                '&format=json'
    border-bottom: 1px solid rgba(0,61,130,0.1);
            );
}
        })
        .then(function(r) { return r.json(); })
        .then(function(data) {
            var pages = Object.values(data.query.pages);
            list.innerHTML = '';


#random-articles-list {
            var promises = pages.map(function(page) {
    padding: 12px;
                var title = page.title;
    display: flex;
                var pageUrl = mw.config.get('wgArticlePath').replace(
    flex-direction: column;
                    '$1', encodeURIComponent(title.replace(/ /g, '_'))
    gap: 12px;
                );
}


.random-article-card {
                var content = '';
    display: flex;
                if (page.revisions && page.revisions[0]) {
    gap: 14px;
                    content = page.revisions[0]['*'] || '';
    padding: 14px;
                }
    border-radius: 12px;
    background: rgba(210, 230, 255, 0.12);
    border: 1px solid rgba(0,61,130,0.07);
    text-decoration: none;
    color: inherit;
    transition: all 0.22s ease;
    align-items: flex-start;
}


.random-article-card:hover {
                var excerpt = extractDescription(content);
    background: rgba(210, 230, 255, 0.35);
                if (!excerpt) excerpt = 'Немає опису.';
    border-color: rgba(0,61,130,0.18);
    transform: translateX(3px);
    text-decoration: none;
}


.random-article-thumb {
                var imgName = extractImageName(content);
    width: 90px;
    height: 90px;
    border-radius: 10px;
    object-fit: cover;
    flex-shrink: 0;
    background: #eef2f8;
}


.random-article-thumb-placeholder {
                if (imgName) {
    width: 90px;
                    var fileTitle = imgName.match(/^(Файл|File|Image|Зображення):/i)
    height: 90px;
                        ? imgName
    border-radius: 10px;
                        : 'File:' + imgName;
    flex-shrink: 0;
    background: linear-gradient(135deg, #e8eef7, #c8d8ee);
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 22px;
}


.random-article-info {
                    return fetch(
    flex: 1;
                        apiBase +
    min-width: 0;
                        '?action=query' +
}
                        '&titles=' + encodeURIComponent(fileTitle) +
                        '&prop=imageinfo' +
                        '&iiprop=url' +
                        '&iiurlwidth=120' +
                        '&format=json'
                    )
                    .then(function(r) { return r.json(); })
                    .then(function(imgData) {
                        var imgPages = Object.values(imgData.query.pages);
                        var imgSrc = null;
                        if (imgPages[0] && imgPages[0].imageinfo && imgPages[0].imageinfo[0]) {
                            imgSrc = imgPages[0].imageinfo[0].thumburl || imgPages[0].imageinfo[0].url;
                        }
                        return { title: title, excerpt: excerpt, pageUrl: pageUrl, imgSrc: imgSrc };
                    })
                    .catch(function() {
                        return { title: title, excerpt: excerpt, pageUrl: pageUrl, imgSrc: null };
                    });
                }


.random-article-title {
                return Promise.resolve({ title: title, excerpt: excerpt, pageUrl: pageUrl, imgSrc: null });
    font-family: system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
            });
    font-size: 15px;
    font-weight: 700;
    color: #003d82;
    margin-bottom: 6px;
    line-height: 1.35;
    overflow: hidden;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
}


.random-article-excerpt {
            return Promise.all(promises);
    font-family: system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
        })
    font-size: 13px;
        .then(function(results) {
    color: #555;
            var list2 = document.getElementById('random-articles-list');
    line-height: 1.45;
            if (!list2) return;
    overflow: hidden;
            list2.innerHTML = '';
    display: -webkit-box;
    -webkit-line-clamp: 3;
    -webkit-box-orient: vertical;
}


.random-articles-loading {
            results.forEach(function(item) {
    padding: 20px;
                var thumbHtml = item.imgSrc
    text-align: center;
                    ? '<div class="random-article-thumb-wrap"><img class="random-article-thumb" src="' + item.imgSrc + '" alt=""></div>'
    color: #888;
                    : '<div class="random-article-thumb-placeholder">📄</div>';
    font-size: 13px;
    font-family: system-ui, sans-serif;
}


.random-articles-refresh {
                var card = document.createElement('a');
    display: none;
                card.href = item.pageUrl;
}
                card.className = 'random-article-card';
                card.innerHTML =
                    thumbHtml +
                    '<div class="random-article-info">' +
                        '<div class="random-article-title">' + mw.html.escape(item.title) + '</div>' +
                        '<div class="random-article-excerpt">' + mw.html.escape(item.excerpt) + '</div>' +
                    '</div>';


/* ════════════════════════════════════
                list2.appendChild(card);
  РЕСУРСИ ТА ПОСИЛАННЯ
            });
═══════════════════════════════════════ */
        })
.resources-and-contacts {
        .catch(function(err) {
    display: flex;
            var list3 = document.getElementById('random-articles-list');
    flex-wrap: wrap;
            if (list3) list3.innerHTML = '<div class="random-articles-loading">Не вдалося завантажити статті.</div>';
    gap: 28px;
            console.error('[RA] error:', err);
    margin: 30px 0 50px;
        });
    align-items: stretch;
}
}


.resource-block,
mw.hook('wikipage.content').add(function() {
.contacts-block {
     var panel = document.getElementById('random-articles-panel');
    flex: 1;
     if (!panel) return;
    min-width: 300px;
    background: rgba(220, 235, 255, 0.18);
    border: 1px solid rgba(180, 210, 240, 0.5);
     border-radius: 14px;
     padding: 28px 32px;
    box-shadow: 0 4px 12px rgba(0,61,130,0.06);
    box-sizing: border-box;
    display: flex;
    flex-direction: column;
}


.resource-block ul,
     loadRandomArticles();
.contacts-block ul {
     flex: 1;
    list-style: none;
    padding-left: 0;
    margin: 0;
}


.resource-block h2,
    var btn = document.getElementById('random-articles-refresh');
.contacts-block h2 {
     if (btn) {
    font-size: 1.3rem !important;
        btn.addEventListener('click', function() {
     font-weight: 700 !important;
            loadRandomArticles();
    color: #003d82 !important;
        });
    margin: 0 0 20px 0 !important;
     }
    padding: 0 0 14px 0 !important;
});
     border: none !important;
    border-bottom: 2px solid rgba(0,61,130,0.12) !important;
    line-height: 1.3 !important;
}


.resource-block li,
/* ══════════════════════════════════════════════
.contacts-block li {
  Vue-додаток для категорій MediaWiki
    margin-bottom: 11px;
══════════════════════════════════════════════ */
    line-height: 1.6;
    font-size: 1rem;
    color: #444;
    padding-left: 14px;
    position: relative;
}


.resource-block li::before,
mw.hook('wikipage.content').add(function () {
.contacts-block li::before {
     var mountEl = document.getElementById('vue-category-cards');
     content: '';
     if (!mountEl) return;
     position: absolute;
    left: 0;
    color: #003d82;
    font-weight: 700;
    opacity: 0.5;
}


.resource-block li a,
    var categoryName    = mountEl.getAttribute('data-category')          || '';
.contacts-block li a {
    var filterField    = mountEl.getAttribute('data-filter-field')      || 'auto';
     color: #1e40af;
    var pageLimit      = parseInt(mountEl.getAttribute('data-limit')    || '0', 10);
     text-decoration: none;
    var columns        = mountEl.getAttribute('data-columns')          || '3';
     transition: color 0.2s;
     var dataFilters    = mountEl.getAttribute('data-filters')          || '';
}
     var dataSortOrder  = mountEl.getAttribute('data-sort-order')        || '';
     var filterFromTitle = mountEl.getAttribute('data-filter-from-title') === 'true';


.resource-block li a:hover,
    var fixedFilters = dataFilters
.contacts-block li a:hover {
        ? dataFilters.split(',').map(function(s){ return s.trim(); }).filter(Boolean)
    color: #003d82;
        : [];
     text-decoration: underline;
     var sortOrder = dataSortOrder
}
        ? dataSortOrder.split(',').map(function(s){ return s.trim(); }).filter(Boolean)
        : [];


/* ════════════════════════════════════
    if (!categoryName) {
  АДАПТИВНІСТЬ
        mountEl.innerHTML = '<p style="color:red">Вкажіть атрибут data-category</p>';
═══════════════════════════════════════ */
         return;
@media (max-width: 1100px) {
    .welcome-wrapper {
        flex-direction: column;
         text-align: center;
     }
     }
    .stats-panel {
        width: 100%;
        max-width: 400px;
    }
    .main-content-layout {
        flex-direction: column;
    }
    .right-column {
        width: 100%;
        min-width: unset;
        flex-direction: row;
        flex-wrap: wrap;
    }
    .category-grid-container {
        grid-template-columns: repeat(3, 1fr);
    }
}


@media (max-width: 820px) {
    var isTouch = ('ontouchstart' in window) || (navigator.maxTouchPoints > 0);
     .category-grid-container {
 
        grid-template-columns: repeat(2, 1fr);
    mw.loader.getScript('https://unpkg.com/vue@3/dist/vue.global.prod.js').then(function () {
     }
 
}
        var apiBase = mw.config.get('wgScriptPath') + '/api.php';
 
        function parseInfobox(wikitext) {
            if (!wikitext) return {};
            var fields = {};
            var depth = 0, start = -1, end = -1;
            for (var i = 0; i < wikitext.length; i++) {
                if (wikitext[i] === '{' && wikitext[i + 1] === '{') {
                    if (depth === 0) start = i;
                    depth++;
                    i++;
                } else if (wikitext[i] === '}' && wikitext[i + 1] === '}') {
                    depth--;
                    if (depth === 0) { end = i + 2; break; }
                    i++;
                }
            }
            var box = (start >= 0 && end > start) ? wikitext.substring(start, end) : wikitext;
            var lineRe = /\|\s*([\w\u0400-\u04FF]+)\s*=\s*([^\|\n\}]*)/gi;
            var m;
            while ((m = lineRe.exec(box)) !== null) {
                var key = m[1].trim().toLowerCase();
                if (key === 'class' || key === 'style') continue;
                var val = m[2].trim()
                    .replace(/\[\[(?:[^\|\]]*\|)?([^\]]+)\]\]/g, '$1')
                    .replace(/'{2,3}/g, '')
                    .replace(/<[^>]+>/g, '');
                if (val) fields[key] = val;
            }
            return fields;
        }
 
        function resolveFilterValue(fields, explicit) {
            if (!explicit || explicit === 'auto') {
                var priority = ['посада', 'position', 'title', 'rank', 'тип', 'type', 'категорія', 'рубрика'];
                for (var i = 0; i < priority.length; i++) {
                    if (fields[priority[i]]) return fields[priority[i]];
                }
                var skip = ['image', 'зображення', 'photo', 'фото'];
                var keys = Object.keys(fields);
                for (var j = 0; j < keys.length; j++) {
                    if (skip.indexOf(keys[j]) === -1) return fields[keys[j]];
                }
                return '';
            }
            return fields[explicit.toLowerCase()] || '';
        }
 
        function filterLabelFromTitle(pageTitle) {
            if (!fixedFilters.length || !pageTitle) return 'Інше';
            var lower = pageTitle.toLowerCase();
            for (var i = 0; i < fixedFilters.length; i++) {
                if (lower.indexOf(fixedFilters[i].toLowerCase()) !== -1) {
                    return fixedFilters[i];
                }
            }
            return 'Інше';
        }
 
        function matchFixedFilter(rawVal) {
            if (!fixedFilters.length || !rawVal) return rawVal;
            var lower = rawVal.toLowerCase();
            for (var i = 0; i < fixedFilters.length; i++) {
                if (lower.indexOf(fixedFilters[i].toLowerCase()) !== -1 ||
                    fixedFilters[i].toLowerCase().indexOf(lower) !== -1) {
                    return fixedFilters[i];
                }
            }
            return rawVal;
        }
 
        function toFilterLabel(val) {
            if (!val) return 'Інше';
            if (fixedFilters.length) return val;
            if (val.length <= 12) return val;
            return val.split(/[\s,]/)[0];
        }
 
        function sortItems(items) {
            if (!sortOrder.length) {
                return items.slice().sort(function(a, b) {
                    return a.title.localeCompare(b.title, 'uk');
                });
            }
            return items.slice().sort(function(a, b) {
                var ai = sortOrder.indexOf(a.filterLabel);
                var bi = sortOrder.indexOf(b.filterLabel);
                if (ai === -1) ai = sortOrder.length;
                if (bi === -1) bi = sortOrder.length;
                if (ai !== bi) return ai - bi;
                return a.title.localeCompare(b.title, 'uk');
            });
        }
 
        var app = Vue.createApp({
            data() {
                return {
                    items:        [],
                    loading:      true,
                    error:        null,
                    activeFilter: 'Всі',
                    filters:      ['Всі'],
                    preview:      null,
                    previewX:    0,
                    previewY:     0,
                    previewTimer: null,
                    searchQuery:  '',
                    gridColumns:  columns,
                    isTouch:      isTouch,
                };
            },
 
            computed: {
                filteredItems() {
                    var vm = this;
                    var q = vm.searchQuery.trim().toLowerCase();
                    var base = vm.items.filter(function (item) {
                        if (!item || !item.title) return false;
                        var matchFilter = vm.activeFilter === 'Всі' || item.filterLabel === vm.activeFilter;
                        var matchSearch = !q ||
                            item.title.toLowerCase().indexOf(q) !== -1 ||
                            (item.description && item.description.toLowerCase().indexOf(q) !== -1);
                        return matchFilter && matchSearch;
                    });
                    return sortItems(base);
                },
 
                gridStyle() {
                    if (window.innerWidth <= 480) return 'grid-template-columns: 1fr;';
                    return 'grid-template-columns: repeat(' + this.gridColumns + ', 1fr);';
                }
            },
 
            mounted() {
                this.loadItems();
            },
 
            methods: {
                showPreview(item, event) {
                    if (this.isTouch || !item) return;
                    var vm = this;
                    clearTimeout(vm.previewTimer);
                    var rect = (event.currentTarget || event.target).getBoundingClientRect();
                    var scrollY = window.scrollY || window.pageYOffset;
                    var scrollX = window.scrollX || window.pageXOffset;
                    vm.previewTimer = setTimeout(function () {
                        var spaceRight = window.innerWidth - rect.right;
                        vm.previewX = spaceRight > 290
                            ? rect.right + scrollX + 12
                            : rect.left + scrollX - 282;
                        vm.previewY = rect.top + scrollY;
                        vm.preview  = item;
                    }, 250);
                },
                hidePreview() {
                    if (this.isTouch) return;
                    clearTimeout(this.previewTimer);
                    this.previewTimer = setTimeout(() => { this.preview = null; }, 150);
                },
                keepPreview() {
                    if (this.isTouch) return;
                    clearTimeout(this.previewTimer);
                },
 
                async loadItems() {
                    this.loading = true;
                    this.error  = null;
                    try {
                        // ── 1. Збираємо ВСІХ членів категорії через cmcontinue ──
                        var members = [];
                        var continueToken = null;
 
                        do {
                            var url = apiBase +
                                '?action=query&list=categorymembers' +
                                '&cmtitle=' + encodeURIComponent('Категорія:' + categoryName) +
                                '&cmlimit=500&cmnamespace=0&format=json';
 
                            if (continueToken) {
                                url += '&cmcontinue=' + encodeURIComponent(continueToken);
                            }
 
                            var catResp = await fetch(url);
                            var catData = await catResp.json();
                            var batch = (catData.query || {}).categorymembers || [];
                            members = members.concat(batch);
 
                            continueToken = (catData.continue && catData.continue.cmcontinue)
                                ? catData.continue.cmcontinue
                                : null;
 
                        } while (continueToken);
 
                        // Якщо data-limit заданий явно — обрізаємо
                        if (pageLimit && pageLimit < members.length) {
                            members = members.slice(0, pageLimit);
                        }
 
                        if (!members.length) { this.loading = false; return; }
 
                        // ── 2. Завантажуємо вміст сторінок батчами по 50 ──
                        var pages = [];
                        var batchSize = 50;
 
                        for (var offset = 0; offset < members.length; offset += batchSize) {
                            var batchMembers = members.slice(offset, offset + batchSize);
                            var titles = batchMembers.map(function(m) { return m.title; }).join('|');
 
                            var pageResp = await fetch(
                                apiBase + '?action=query&titles=' + encodeURIComponent(titles) +
                                '&prop=revisions&rvprop=content&format=json'
                            );
                            var pageData = await pageResp.json();
                            var batchPages = Object.values((pageData.query || {}).pages || {});
                            pages = pages.concat(batchPages);
                        }
 
                        // ── 3. Обробляємо кожну сторінку ──
                        var filterSet = new Set();
 
                        var promises = pages.map(async function(page) {
                            try {
                                var content = (page.revisions && page.revisions[0])
                                    ? (page.revisions[0]['*'] || '') : '';
 
                                var filterLabel;
 
                                if (filterFromTitle) {
                                    filterLabel = filterLabelFromTitle(page.title);
                                } else {
                                    var fields  = parseInfobox(content);
                                    var rawVal  = resolveFilterValue(fields, filterField === 'auto' ? 'auto' : filterField);
                                    var matched = fixedFilters.length ? matchFixedFilter(rawVal) : rawVal;
                                    filterLabel = toFilterLabel(matched);
                                }
 
                                if (filterLabel && filterLabel !== 'Інше') filterSet.add(filterLabel);
 
                                var description = extractDescription(content);
                                var imgName    = extractImageName(content);
                                var imgSrc      = null;
 
                                if (imgName) {
                                    try {
                                        var fileTitle = /^(Файл|File|Image|Зображення):/i.test(imgName)
                                            ? imgName : 'File:' + imgName;
                                        var imgResp = await fetch(
                                            apiBase + '?action=query&titles=' + encodeURIComponent(fileTitle) +
                                            '&prop=imageinfo&iiprop=url&iiurlwidth=200&format=json'
                                        );
                                        var imgData  = await imgResp.json();
                                        var imgPages = Object.values((imgData.query || {}).pages || {});
                                        var ii = imgPages[0] && imgPages[0].imageinfo && imgPages[0].imageinfo[0];
                                        if (ii) imgSrc = ii.thumburl || ii.url;
                                    } catch (e) { /* ignore */ }
                                }
 
                                var pageUrl = mw.config.get('wgArticlePath').replace(
                                    '$1', encodeURIComponent(page.title.replace(/ /g, '_'))
                                );
 
                                var extra = [];
                                if (!filterFromTitle) {
                                    var fields2  = parseInfobox(content);
                                    var extraKeys = ['посада', 'position', 'occupation', 'спеціальність',
                                                    'рік', 'рубрика', 'тип', 'автор', 'faculty'];
                                    extraKeys.forEach(function(k) {
                                        if (fields2[k]) extra.push({ label: k, value: fields2[k] });
                                    });
                                }
 
                                return {
                                    title:      page.title,
                                    filterLabel: filterLabel || 'Інше',
                                    description: description || '',
                                    imgSrc:      imgSrc,
                                    pageUrl:     pageUrl,
                                    extra:      extra.slice(0, 3),
                                };
                            } catch (e) {
                                console.error('[vcc] page error:', e, page && page.title);
                                return null;
                            }
                        });
 
                        var results = await Promise.all(promises);
                        this.items = results.filter(function(item) { return item != null; });
 
                        // ── 4. Будуємо список фільтрів ──
                        var builtFilters;
                        if (fixedFilters.length) {
                            var itemsRef = this.items;
                            builtFilters = fixedFilters.filter(function(f) {
                                return itemsRef.some(function(item) { return item.filterLabel === f; });
                            });
                        } else {
                            builtFilters = Array.from(filterSet).sort(function(a, b) {
                                return a.localeCompare(b, 'uk');
                            });
                        }
                        this.filters = ['Всі'].concat(builtFilters);
 
                    } catch (e) {
                        console.error('[vue-category-cards] error:', e);
                        this.error = 'Не вдалося завантажити дані.';
                    }
                    this.loading = false;
                }
            },
 
            template: `
<div class="vcc-app">
 
  <div class="vcc-topbar">
    <input
      class="vcc-search"
      type="text"
      v-model="searchQuery"
      placeholder="Пошук..."
    />
    <span class="vcc-count" v-if="!loading">
      Знайдено: <strong>{{ filteredItems.length }}</strong> з {{ items.length }}
    </span>
  </div>
 
  <div class="vcc-layout">


@media (max-width: 520px) {
     <div class="vcc-main">
    .category-grid-container {
        grid-template-columns: 1fr;
    }
    .welcome-title { font-size: 2rem; }
     .welcome-subtitle { font-size: 1.25rem; }
    .section-categories { font-size: 1.8rem; }
}


@media (max-width: 900px) {
      <div class="vcc-loading" v-if="loading">
    .resources-and-contacts {
         <div class="vcc-spinner"></div>
         flex-direction: column;
         <span>Завантаження...</span>
         gap: 20px;
      </div>
    }
}


/* ── Ліва колонка з заголовком і сіткою ── */
      <div class="vcc-error" v-else-if="error">{{ error }}</div>
.category-column {
    flex: 1;
    min-width: 0;
    display: flex;
    flex-direction: column;
}


.category-column .category-grid-container {
      <div class="vcc-empty" v-else-if="!filteredItems.length">
    flex: 1;
        <div class="vcc-empty-icon">🔍</div>
}
        <p>Нічого не знайдено</p>
        <button class="vcc-reset-btn" @click="activeFilter = 'Всі'; searchQuery = ''">
          Скинути фільтри
        </button>
      </div>


      <div class="vcc-grid" :style="gridStyle" v-else>
        <a
          v-for="item in filteredItems"
          :key="item.title"
          :href="item.pageUrl"
          class="vcc-card"
          @mouseenter="showPreview(item, $event)"
          @mouseleave="hidePreview"
        >
          <div class="vcc-card-img-wrap">
            <img v-if="item.imgSrc" :src="item.imgSrc" :alt="item.title" class="vcc-card-img" />
            <div v-else class="vcc-card-img-placeholder">{{ item.title.charAt(0) }}</div>
          </div>
          <div class="vcc-card-body">
            <div v-if="item.filterLabel && item.filterLabel !== 'Інше'"
                class="vcc-card-badge">{{ item.filterLabel }}</div>
            <div class="vcc-card-name">{{ item.title }}</div>
            <div class="vcc-card-desc" v-if="item.description">{{ item.description }}</div>
          </div>
        </a>
      </div>
    </div>


     .timeline-dot {
     <div class="vcc-sidebar" v-if="filters.length > 2">
         left: -33px;
      <div class="vcc-sidebar-title">Фільтр</div>
    }
      <div class="vcc-filters">
    .timeline-year {
         <button
        font-size: 1.2rem;
          v-for="f in filters"
    }
          :key="f"
    .timeline-event {
          class="vcc-filter-btn"
        font-size: 14px;
          :class="{ active: activeFilter === f }"
     }
          @click="activeFilter = f"
}
        >{{ f }}</button>
      </div>
     </div>


  </div>


  <teleport to="body" v-if="!isTouch">
    <a
      v-if="preview && preview.title"
      :href="preview.pageUrl"
      class="vcc-preview"
      :style="{ top: previewY + 'px', left: previewX + 'px' }"
      @mouseenter="keepPreview"
      @mouseleave="hidePreview"
    >
      <div class="vcc-preview-top">
        <img v-if="preview.imgSrc" :src="preview.imgSrc" class="vcc-preview-img" :alt="preview.title" />
        <div v-else class="vcc-preview-img-placeholder">{{ preview.title.charAt(0) }}</div>
        <div class="vcc-preview-info">
          <div class="vcc-preview-badge" v-if="preview.filterLabel && preview.filterLabel !== 'Інше'">
            {{ preview.filterLabel }}
          </div>
          <div class="vcc-preview-name">{{ preview.title }}</div>
        </div>
      </div>
      <div class="vcc-preview-divider"></div>
      <div class="vcc-preview-desc" v-if="preview.description">{{ preview.description }}</div>
      <div class="vcc-preview-row" v-for="e in preview.extra" :key="e.label">
        <span class="vcc-preview-lbl">{{ e.label }}</span>
        <span class="vcc-preview-val">{{ e.value }}</span>
      </div>
    </a>
  </teleport>


</div>
            `
        });


        app.mount('#vue-category-cards');
    });
});


/* ══════════════════════════════════════════════
/* ══════════════════════════════════════════════
   MODERN UI: градієнти, glassmorphism, анімації
   ГОЛОВНА СТОРІНКА
══════════════════════════════════════════════ */
══════════════════════════════════════════════ */


/* ── Прогрес скролла ── */
function animateNumber(element, target) {
.scroll-progress {
     element.classList.add('animating');
     position: fixed;
     var current = 0;
     top: 0;
     var increment = target / 60;
     left: 0;
     var timer = setInterval(function() {
     height: 4px;
        current += increment;
    background: linear-gradient(90deg, #003d82, #0066cc, #ffd700);
        if (current >= target) {
    z-index: 99999;
            current = target;
    transition: width 0.1s ease;
            clearInterval(timer);
     box-shadow: 0 2px 8px rgba(0, 61, 130, 0.3);
            setTimeout(function() { element.classList.remove('animating'); }, 100);
        }
        element.textContent = Math.floor(current);
     }, 16);
}
}


/* ── Градієнтний фон для welcome ── */
mw.hook('wikipage.content').add(function() {
.welcome-wrapper {
    if (mw.config.get('wgPageName') !== 'Головна_сторінка') return;
    background: linear-gradient(180deg,
 
         rgba(210, 230, 255, 0.4) 0%,
    var statsNumbers = document.querySelectorAll('.stats-panel-number');
        rgba(210, 230, 255, 0.25) 40%,
    var animated = false;
         rgba(255, 255, 255, 0) 100%);
 
     position: relative;
    function checkAndAnimate() {
    overflow: hidden;
        if (animated) return;
    padding-bottom: 60px !important;
        var statsPanel = document.querySelector('.stats-panel');
}
        if (!statsPanel) return;
 
        var rect = statsPanel.getBoundingClientRect();
         if (rect.top < window.innerHeight && rect.bottom > 0) {
            animated = true;
            statsNumbers.forEach(function(el) {
                var text = el.textContent.trim();
                var num = parseInt(text.replace(/[^\d]/g, ''), 10);
                if (!isNaN(num) && num > 0) {
                    el.textContent = '0';
                    setTimeout(function() { animateNumber(el, num); }, 200);
                }
            });
         }
    }
 
    window.addEventListener('scroll', checkAndAnimate);
    checkAndAnimate();
});
 
mw.hook('wikipage.content').add(function() {
     document.querySelectorAll('div[style*="grid-template-columns"]').forEach(function(grid) {
        var cards = Array.from(grid.children);
        if (cards.length < 2) return;
 
        cards.sort(function(a, b) {
            var aLink = a.querySelector('div[style*="flex-grow"] a');
            var bLink = b.querySelector('div[style*="flex-grow"] a');
            if (!aLink || !bLink) return 0;
 
            var aSurname = aLink.textContent.trim().split(' ')[0];
            var bSurname = bLink.textContent.trim().split(' ')[0];


/* Плавний перехід до білого фону */
            return aSurname.localeCompare(bSurname, 'uk');
.welcome-wrapper::after {
        });
    content: '';
    position: absolute;
    bottom: 0;
    left: 0;
    right: 0;
    height: 80px;
    background: linear-gradient(to bottom, transparent, white);
    pointer-events: none;
    z-index: 1;
}


.welcome-text,
        cards.forEach(function(card) {
.stats-panel {
            grid.appendChild(card);
    position: relative;
        });
     z-index: 2;
     });
}
});


/* ── Glassmorphism для статистики ── */
mw.hook('wikipage.content').add(function() {
.stats-panel {
     if (mw.config.get('wgPageName') !== 'Головна_сторінка') return;
    background: rgba(255, 255, 255, 0.7) !important;
    backdrop-filter: blur(10px);
    -webkit-backdrop-filter: blur(10px);
     border: 1px solid rgba(255, 255, 255, 0.3) !important;
    box-shadow: 0 8px 32px rgba(0, 61, 130, 0.15) !important;
}


.stats-panel-header {
    var progressBar = document.createElement('div');
     background: linear-gradient(135deg, rgba(0, 61, 130, 0.1), rgba(0, 102, 204, 0.15)) !important;
    progressBar.className = 'scroll-progress';
}
     document.body.appendChild(progressBar);


/* ── Glassmorphism для випадкових статей ── */
    function updateProgress() {
.random-articles-panel {
        var winScroll = document.documentElement.scrollTop || document.body.scrollTop;
    background: rgba(255, 255, 255, 0.75) !important;
        var height = document.documentElement.scrollHeight - document.documentElement.clientHeight;
    backdrop-filter: blur(12px);
        if (height <= 0) return;
    -webkit-backdrop-filter: blur(12px);
        var scrolled = (winScroll / height) * 100;
    border: 1px solid rgba(255, 255, 255, 0.3) !important;
        progressBar.style.width = scrolled + '%';
}
    }


/* ── Градієнтні картки категорій ── */
    window.addEventListener('scroll', updateProgress, { passive: true });
.category-card {
     updateProgress();
    background: linear-gradient(135deg, #ffffff 0%, #f8fbff 100%);
});
     border: 1px solid rgba(0, 61, 130, 0.08);
    position: relative;
    overflow: hidden;
}


.category-card::before {
mw.hook('wikipage.content').add(function() {
    content: '';
     if (mw.config.get('wgPageName') !== 'Головна_сторінка') return;
    position: absolute;
    top: -50%;
    left: -50%;
    width: 200%;
    height: 200%;
    background: linear-gradient(135deg, transparent, rgba(0, 61, 130, 0.05), transparent);
     transform: rotate(45deg);
    transition: all 0.6s ease;
    opacity: 0;
}


.category-card:hover::before {
    var welcomeWrapper = document.querySelector('.welcome-wrapper');
    opacity: 1;
     if (!welcomeWrapper) return;
    top: -25%;
     left: -25%;
}


/* ── Мікроанімації: bounce для іконок ── */
    if (window.innerWidth < 768) return;
.category-card:hover .card-image img {
    if (window.matchMedia('(prefers-reduced-motion: reduce)').matches) return;
    animation: icon-bounce 0.6s ease;
}


@keyframes icon-bounce {
    var canvas = document.createElement('canvas');
     0%, 100% { transform: scale(1.12) translateY(0); }
    canvas.className = 'particles-canvas';
    50% { transform: scale(1.12) translateY(-8px); }
     canvas.style.cssText = 'position:absolute;top:0;left:0;width:100%;height:100%;pointer-events:none;z-index:0;';
}


/* ── Gradient hover для карточок ── */
    canvas.style.webkitMaskImage = 'linear-gradient(to bottom, rgba(0,0,0,0) 0%, rgba(0,0,0,1) 10%, rgba(0,0,0,1) 90%, rgba(0,0,0,0) 100%), linear-gradient(to right, rgba(0,0,0,0) 0%, rgba(0,0,0,1) 10%, rgba(0,0,0,1) 90%, rgba(0,0,0,0) 100%)';
.category-card {
     canvas.style.maskImage = 'linear-gradient(to bottom, rgba(0,0,0,0) 0%, rgba(0,0,0,1) 10%, rgba(0,0,0,1) 90%, rgba(0,0,0,0) 100%), linear-gradient(to right, rgba(0,0,0,0) 0%, rgba(0,0,0,1) 10%, rgba(0,0,0,1) 90%, rgba(0,0,0,0) 100%)';
     transition: all 0.4s cubic-bezier(0.165, 0.84, 0.44, 1);
    canvas.style.webkitMaskComposite = 'source-in';
}
    canvas.style.maskComposite = 'intersect';
    welcomeWrapper.style.position = 'relative';
    welcomeWrapper.insertBefore(canvas, welcomeWrapper.firstChild);


.category-card:hover {
    var ctx = canvas.getContext('2d');
     transform: translateY(-8px) scale(1.02);
     canvas.width = welcomeWrapper.offsetWidth;
     box-shadow: 0 24px 48px rgba(0, 61, 130, 0.2);
     canvas.height = welcomeWrapper.offsetHeight;
}


/* ── Pulse для чисел статистики ── */
    var particles = [];
.stats-panel-number {
    var particleCount = 40;
     animation: number-pulse 2s ease-in-out infinite;
     var animId;
}


@keyframes number-pulse {
    function Particle() {
    0%, 100% { transform: scale(1); }
        this.x = Math.random() * canvas.width;
    50% { transform: scale(1.05); color: #0066cc; }
        this.y = Math.random() * canvas.height;
}
        this.vx = (Math.random() - 0.5) * 0.5;
        this.vy = (Math.random() - 0.5) * 0.5;
        this.radius = Math.random() * 2 + 1;
    }


/* ── Rainbow effect для анімації чисел ── */
    Particle.prototype.draw = function() {
@keyframes rainbow {
        ctx.beginPath();
    0% { color: #003d82; }
        ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2);
    25% { color: #0066cc; }
        ctx.fillStyle = 'rgba(255, 215, 0, 0.6)';
    50% { color: #4a90e2; }
        ctx.fill();
     75% { color: #0066cc; }
     };
    100% { color: #003d82; }
}


.stats-panel-number.animating {
    Particle.prototype.update = function() {
    animation: rainbow 1.5s ease-in-out;
        if (this.x > canvas.width || this.x < 0) this.vx = -this.vx;
}
        if (this.y > canvas.height || this.y < 0) this.vy = -this.vy;
        this.x += this.vx;
        this.y += this.vy;
        this.draw();
    };


/* ── Gradient title ── */
     for (var i = 0; i < particleCount; i++) {
.welcome-title {
        particles.push(new Particle());
     background: linear-gradient(135deg, #003d82 0%, #0066cc 50%, #003d82 100%);
     }
    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;
     background-clip: text;
    animation: gradient-shift 3s ease infinite;
    background-size: 200% 200%;
}


@keyframes gradient-shift {
    function animate() {
    0%, 100% { background-position: 0% 50%; }
        ctx.clearRect(0, 0, canvas.width, canvas.height);
    50% { background-position: 100% 50%; }
}


/* ── Smooth reveal для карточок ── */
        for (var i = 0; i < particles.length; i++) {
.category-card {
            particles[i].update();
    /* AOS сам додає opacity при ініціалізації */
            for (var j = i + 1; j < particles.length; j++) {
}
                var dx = particles[i].x - particles[j].x;
                var dy = particles[i].y - particles[j].y;
                var distance = Math.sqrt(dx * dx + dy * dy);


/* ── Неоморфізм для випадкових статей ── */
                if (distance < 120) {
.random-article-card {
                    ctx.beginPath();
    background: linear-gradient(145deg, #ffffff, #f0f6ff);
                    ctx.strokeStyle = 'rgba(255, 215, 0, ' + (1 - distance / 120) * 0.3 + ')';
    box-shadow:
                    ctx.lineWidth = 1;
        8px 8px 16px rgba(0, 61, 130, 0.08),
                    ctx.moveTo(particles[i].x, particles[i].y);
        -8px -8px 16px rgba(255, 255, 255, 0.9);
                    ctx.lineTo(particles[j].x, particles[j].y);
    border: none !important;
                    ctx.stroke();
}
                }
            }
        }


.random-article-card:hover {
         animId = requestAnimationFrame(animate);
    box-shadow:
     }
         12px 12px 24px rgba(0, 61, 130, 0.12),
        -12px -12px 24px rgba(255, 255, 255, 1);
     background: linear-gradient(145deg, #f0f6ff, #ffffff);
}


/* ── Glassmorphism для заголовків ── */
     animate();
.section-categories {
     text-shadow: 0 2px 8px rgba(0, 61, 130, 0.1);
}


/* ── Gradient підкреслення ── */
    var resizeTimer;
.section-categories::after {
    window.addEventListener('resize', function() {
    background: linear-gradient(90deg, #ffd700, #ffed4e, #ffd700) !important;
        clearTimeout(resizeTimer);
     box-shadow: 0 2px 8px rgba(255, 215, 0, 0.4);
        resizeTimer = setTimeout(function() {
}
            canvas.width = welcomeWrapper.offsetWidth;
            canvas.height = welcomeWrapper.offsetHeight;
            if (window.innerWidth < 768) {
                cancelAnimationFrame(animId);
                canvas.remove();
            }
        }, 200);
     });
});

Поточна версія на 17:35, 25 квітня 2026

// Виправляємо viewport
(function() {
    var viewport = document.querySelector('meta[name="viewport"]');
    if (viewport) {
        viewport.setAttribute('content', 'width=device-width, initial-scale=1.0, maximum-scale=5.0, viewport-fit=cover');
    } else {
        var meta = document.createElement('meta');
        meta.name = 'viewport';
        meta.content = 'width=device-width, initial-scale=1.0, maximum-scale=5.0, viewport-fit=cover';
        document.head.appendChild(meta);
    }
})();

$(function() {
    $('.category-card').each(function() {
        var $card = $(this);
        var href = $card.attr('data-href');

        if (href) {
            $card.css('cursor', 'pointer');

            $card.on('click', function(e) {
                if ($(e.target).closest('a').length === 0) {
                    window.location.href = href;
                }
            });

            $card.hover(
                function() { $card.addClass('card-hover'); },
                function() { $card.removeClass('card-hover'); }
            );
        }
    });
});

/* ══════════════════════════════════════════════
   МОБІЛЬНА ШАПКА
══════════════════════════════════════════════ */

mw.hook('wikipage.content').add(function() {

    var overlay = document.createElement('div');
    overlay.className = 'mobile-menu-overlay';
    document.body.appendChild(overlay);

    var topbar = document.createElement('div');
    topbar.className = 'mobile-topbar';

    var wikiLogo = document.querySelector('#p-logo img, .mw-wiki-logo img, img.mw-logo-icon, #p-logo a, .mw-logo img');
    var logoSrc = '';
    if (wikiLogo && wikiLogo.tagName === 'IMG') {
        logoSrc = wikiLogo.src;
    } else if (wikiLogo && wikiLogo.tagName === 'A') {
        var bgStyle = window.getComputedStyle(wikiLogo).backgroundImage;
        if (bgStyle && bgStyle !== 'none') {
            var bgMatch = bgStyle.match(/url\(["']?([^"')]+)["']?\)/);
            if (bgMatch) logoSrc = bgMatch[1];
        }
    }
    var mainPageUrl = mw.config.get('wgArticlePath').replace('$1', encodeURIComponent('Головна_сторінка'));
    var siteName = mw.config.get('wgSiteName') || 'Вікі університету';
    var shortName = siteName.replace('Вікі ', '').split(' ').slice(0, 3).join(' ');
    var userName = mw.config.get('wgUserName');
    var isLoggedIn = !!userName;
    var articlePath = mw.config.get('wgArticlePath');

    var logoHtml = logoSrc
        ? '<img src="' + logoSrc + '" alt="Логотип" style="max-width:32px!important;width:32px;height:32px;">'
        : '<span style="display:flex;align-items:center;justify-content:center;width:32px;height:32px;background:#003d82;color:#fff;font-weight:700;font-size:16px;border-radius:8px;flex-shrink:0;">' + (siteName.charAt(0) || 'В') + '</span>';

    var userInitial = isLoggedIn ? (userName.charAt(0).toUpperCase()) : '';
    var userAvatarHtml = isLoggedIn
        ? '<span class="topbar-user-avatar" aria-label="' + mw.html.escape(userName) + '">' + mw.html.escape(userInitial) + '</span>'
        : '<a class="topbar-login-btn" href="' + articlePath.replace('$1', 'Special:UserLogin') + '" aria-label="Увійти"><svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"/><circle cx="12" cy="7" r="4"/></svg></a>';

    var dropdownHtml = isLoggedIn
        ? '<div class="topbar-user-dropdown" id="topbar-user-dropdown">' +
            '<div class="topbar-dropdown-header">' +
                '<span class="topbar-dropdown-avatar">' + mw.html.escape(userInitial) + '</span>' +
                '<span class="topbar-dropdown-name">' + mw.html.escape(userName) + '</span>' +
            '</div>' +
            '<div class="topbar-dropdown-divider"></div>' +
            '<a class="topbar-dropdown-item" href="' + articlePath.replace('$1', 'Користувач:' + encodeURIComponent(userName)) + '">' +
                '<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"/><circle cx="12" cy="7" r="4"/></svg>' +
                'Профіль' +
            '</a>' +
            '<a class="topbar-dropdown-item" href="' + articlePath.replace('$1', 'Special:Preferences') + '">' +
                '<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="3"/><path d="M19.07 4.93a10 10 0 0 1 0 14.14M4.93 4.93a10 10 0 0 0 0 14.14"/></svg>' +
                'Налаштування' +
            '</a>' +
            '<div class="topbar-dropdown-divider"></div>' +
            '<a class="topbar-dropdown-item topbar-dropdown-logout" href="' + mw.config.get('wgScript') + '?title=Special:UserLogout&returnto=Головна_сторінка">' +
                '<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4"/><polyline points="16 17 21 12 16 7"/><line x1="21" y1="12" x2="9" y2="12"/></svg>' +
                'Вийти' +
            '</a>' +
        '</div>'
        : '';

    topbar.innerHTML =
        '<button class="topbar-menu-btn" id="topbar-menu-btn" aria-label="Меню">' +
            '<span class="topbar-hamburger"><span></span><span></span><span></span></span>' +
        '</button>' +
        '<a class="mobile-topbar-logo" href="' + mainPageUrl + '" aria-label="На головну">' +
            logoHtml +
            '<span class="mobile-topbar-logo-text">' + mw.html.escape(shortName) + '</span>' +
        '</a>' +
        '<div class="mobile-topbar-search" id="mobile-topbar-search-slot"></div>' +
        '<div class="topbar-user-wrap" id="topbar-user-wrap">' +
            userAvatarHtml +
            dropdownHtml +
        '</div>';

    document.body.insertBefore(topbar, document.body.firstChild);

    var nativeSearch = document.getElementById('p-search');
    if (!nativeSearch) nativeSearch = document.querySelector('#mw-head #p-search');

    var searchSlot = document.getElementById('mobile-topbar-search-slot');

    if (nativeSearch && searchSlot) {
        var searchOriginalParent = nativeSearch.parentNode;
        var searchOriginalNextSibling = nativeSearch.nextSibling;

        function moveSearchToTopbar() {
            if (!searchSlot.contains(nativeSearch)) {
                searchSlot.appendChild(nativeSearch);
            }
        }

        function moveSearchBack() {
            if (searchSlot.contains(nativeSearch)) {
                if (searchOriginalNextSibling && searchOriginalParent.contains(searchOriginalNextSibling)) {
                    searchOriginalParent.insertBefore(nativeSearch, searchOriginalNextSibling);
                } else {
                    searchOriginalParent.appendChild(nativeSearch);
                }
            }
        }

        if (window.innerWidth <= 1100) {
            moveSearchToTopbar();
        }

        var resizeTimer;
        window.addEventListener('resize', function() {
            clearTimeout(resizeTimer);
            resizeTimer = setTimeout(function() {
                if (window.innerWidth <= 1100) {
                    moveSearchToTopbar();
                } else {
                    moveSearchBack();
                }
            }, 100);
        });
    }

    var userWrap = topbar.querySelector('#topbar-user-wrap');
    var userDropdown = topbar.querySelector('#topbar-user-dropdown');
    if (userWrap && userDropdown) {
        userWrap.addEventListener('click', function(e) {
            e.stopPropagation();
            var isOpen = userDropdown.classList.contains('open');
            userDropdown.classList.toggle('open', !isOpen);
        });
        document.addEventListener('click', function() {
            userDropdown.classList.remove('open');
        });
    }

    function openMenu() {
        document.body.classList.add('mobile-nav-open');
        overlay.classList.add('open');
        var menuBtn = topbar.querySelector('#topbar-menu-btn');
        if (menuBtn) menuBtn.classList.add('active');
    }

    function closeMenu() {
        document.body.classList.remove('mobile-nav-open');
        overlay.classList.remove('open');
        var menuBtn = topbar.querySelector('#topbar-menu-btn');
        if (menuBtn) menuBtn.classList.remove('active');
    }

    var topbarMenuBtn = topbar.querySelector('#topbar-menu-btn');
    if (topbarMenuBtn) {
        topbarMenuBtn.addEventListener('click', function(e) {
            e.stopPropagation();
            if (document.body.classList.contains('mobile-nav-open')) {
                closeMenu();
            } else {
                openMenu();
            }
        });
    }

    overlay.addEventListener('click', closeMenu);

    document.addEventListener('keydown', function(e) {
        if (e.key === 'Escape') closeMenu();
    });

    window.addEventListener('resize', function() {
        if (window.innerWidth > 1100) closeMenu();
    });
});


/* ══════════════════════════════════════════════
   МОБІЛЬНИЙ ФІК РОЗМІРУ THUMB-КАРТИНОК
══════════════════════════════════════════════ */
mw.hook('wikipage.content').add(function() {
    function fixThumbWidths() {
        if (window.innerWidth > 1100) return;

        var vw = window.innerWidth;
        var targetWidth = Math.min(280, Math.max(120, Math.round(vw * 0.48)));

        document.querySelectorAll('.mw-parser-output .thumbinner').forEach(function(el) {
            el.style.removeProperty('width');
            el.style.setProperty('width', targetWidth + 'px', 'important');
            el.style.setProperty('max-width', '100%', 'important');
            el.style.setProperty('box-sizing', 'border-box', 'important');
        });

        document.querySelectorAll('.mw-parser-output .thumbinner img').forEach(function(el) {
            el.style.setProperty('width', '100%', 'important');
            el.style.setProperty('max-width', '100%', 'important');
            el.style.setProperty('height', 'auto', 'important');
        });
    }

    fixThumbWidths();
    window.addEventListener('resize', fixThumbWidths, { passive: true });
});


/* ══════════════════════════════════════════════
   ГЛОБАЛЬНІ ПАРСЕРИ
══════════════════════════════════════════════ */

function extractImageName(wikitext) {
    if (!wikitext) return null;
    var m = wikitext.match(/\|\s*image\s*=\s*([^\|\n\}]+)/i);
    if (m && m[1].trim()) return m[1].trim();
    m = wikitext.match(/\[\[(?:Файл|File|Зображення|Image):([^\|\]]+)/i);
    return m ? m[1].trim() : null;
}

function extractDescription(wikitext) {
    if (!wikitext) return '';
    var text = wikitext;

    var depth = 0, end = -1;
    for (var i = 0; i < text.length; i++) {
        if (text[i] === '{' && text[i + 1] === '{') { depth++; i++; }
        else if (text[i] === '}' && text[i + 1] === '}') {
            depth--;
            if (depth === 0) { end = i + 2; break; }
            i++;
        }
    }
    if (end > 0) text = text.substring(end);

    text = text
        .replace(/\[\[(?:Файл|File|Зображення|Image):[^\]]*\]\]/gi, '')
        .replace(/\{\|[\s\S]*?\|\}/g, '')
        .replace(/\{\{[^}]*\}\}/g, '')
        .replace(/={2,6}[^=\n]+=+/g, '')
        .replace(/\[\[(?:[^\|\]]*\|)?([^\]]+)\]\]/g, '$1')
        .replace(/\[[^\s\]]+\s+([^\]]+)\]/g, '$1')
        .replace(/\[[^\]]+\]/g, '')
        .replace(/'{2,3}/g, '')
        .replace(/<[^>]+>/g, '')
        .replace(/^[\*#:;].*/gm, '');

    var lines = text.split('\n')
        .map(function (l) { return l.trim(); })
        .filter(function (l) { return l.length > 20; });

    if (!lines.length) return '';
    var result = lines[0].substring(0, 160);
    return lines[0].length > 160 ? result + '…' : result;
}

/* ══════════════════════════════════════════════
   ВИПАДКОВІ СТАТТІ
══════════════════════════════════════════════ */

function loadRandomArticles() {
    var list = document.getElementById('random-articles-list');
    if (!list) return;

    list.innerHTML = '<div class="random-articles-loading">Завантаження...</div>';

    var apiBase = mw.config.get('wgScriptPath') + '/api.php';
    var excludedPages = [
        'Головна сторінка',
        'Структурні підрозділи',
        'Викладачі',
        'Історія університету',
        'Керівництво університету',
        'Факультети і кафедри',
        'Освітні програми',
        'Сертифікатні програми і курси',
        'Періодичні видання',
        'Наукові конференції',
        'Видатні випускники',
        'Історичні постаті',
        'Корпоративна культура'
    ];

    fetch(apiBase + '?action=query&list=random&rnnamespace=0&rnlimit=10&format=json')
        .then(function(r) { return r.json(); })
        .then(function(data) {
            var pages = data.query.random.filter(function(p) {
                return excludedPages.indexOf(p.title) === -1;
            }).slice(0, 3);

            var titles = pages.map(function(p) { return p.title; }).join('|');

            return fetch(
                apiBase +
                '?action=query' +
                '&titles=' + encodeURIComponent(titles) +
                '&prop=revisions' +
                '&rvprop=content' +
                '&format=json'
            );
        })
        .then(function(r) { return r.json(); })
        .then(function(data) {
            var pages = Object.values(data.query.pages);
            list.innerHTML = '';

            var promises = pages.map(function(page) {
                var title = page.title;
                var pageUrl = mw.config.get('wgArticlePath').replace(
                    '$1', encodeURIComponent(title.replace(/ /g, '_'))
                );

                var content = '';
                if (page.revisions && page.revisions[0]) {
                    content = page.revisions[0]['*'] || '';
                }

                var excerpt = extractDescription(content);
                if (!excerpt) excerpt = 'Немає опису.';

                var imgName = extractImageName(content);

                if (imgName) {
                    var fileTitle = imgName.match(/^(Файл|File|Image|Зображення):/i)
                        ? imgName
                        : 'File:' + imgName;

                    return fetch(
                        apiBase +
                        '?action=query' +
                        '&titles=' + encodeURIComponent(fileTitle) +
                        '&prop=imageinfo' +
                        '&iiprop=url' +
                        '&iiurlwidth=120' +
                        '&format=json'
                    )
                    .then(function(r) { return r.json(); })
                    .then(function(imgData) {
                        var imgPages = Object.values(imgData.query.pages);
                        var imgSrc = null;
                        if (imgPages[0] && imgPages[0].imageinfo && imgPages[0].imageinfo[0]) {
                            imgSrc = imgPages[0].imageinfo[0].thumburl || imgPages[0].imageinfo[0].url;
                        }
                        return { title: title, excerpt: excerpt, pageUrl: pageUrl, imgSrc: imgSrc };
                    })
                    .catch(function() {
                        return { title: title, excerpt: excerpt, pageUrl: pageUrl, imgSrc: null };
                    });
                }

                return Promise.resolve({ title: title, excerpt: excerpt, pageUrl: pageUrl, imgSrc: null });
            });

            return Promise.all(promises);
        })
        .then(function(results) {
            var list2 = document.getElementById('random-articles-list');
            if (!list2) return;
            list2.innerHTML = '';

            results.forEach(function(item) {
                var thumbHtml = item.imgSrc
                    ? '<div class="random-article-thumb-wrap"><img class="random-article-thumb" src="' + item.imgSrc + '" alt=""></div>'
                    : '<div class="random-article-thumb-placeholder">📄</div>';

                var card = document.createElement('a');
                card.href = item.pageUrl;
                card.className = 'random-article-card';
                card.innerHTML =
                    thumbHtml +
                    '<div class="random-article-info">' +
                        '<div class="random-article-title">' + mw.html.escape(item.title) + '</div>' +
                        '<div class="random-article-excerpt">' + mw.html.escape(item.excerpt) + '</div>' +
                    '</div>';

                list2.appendChild(card);
            });
        })
        .catch(function(err) {
            var list3 = document.getElementById('random-articles-list');
            if (list3) list3.innerHTML = '<div class="random-articles-loading">Не вдалося завантажити статті.</div>';
            console.error('[RA] error:', err);
        });
}

mw.hook('wikipage.content').add(function() {
    var panel = document.getElementById('random-articles-panel');
    if (!panel) return;

    loadRandomArticles();

    var btn = document.getElementById('random-articles-refresh');
    if (btn) {
        btn.addEventListener('click', function() {
            loadRandomArticles();
        });
    }
});

/* ══════════════════════════════════════════════
   Vue-додаток для категорій MediaWiki
══════════════════════════════════════════════ */

mw.hook('wikipage.content').add(function () {
    var mountEl = document.getElementById('vue-category-cards');
    if (!mountEl) return;

    var categoryName    = mountEl.getAttribute('data-category')          || '';
    var filterField     = mountEl.getAttribute('data-filter-field')      || 'auto';
    var pageLimit       = parseInt(mountEl.getAttribute('data-limit')    || '0', 10);
    var columns         = mountEl.getAttribute('data-columns')           || '3';
    var dataFilters     = mountEl.getAttribute('data-filters')           || '';
    var dataSortOrder   = mountEl.getAttribute('data-sort-order')        || '';
    var filterFromTitle = mountEl.getAttribute('data-filter-from-title') === 'true';

    var fixedFilters = dataFilters
        ? dataFilters.split(',').map(function(s){ return s.trim(); }).filter(Boolean)
        : [];
    var sortOrder = dataSortOrder
        ? dataSortOrder.split(',').map(function(s){ return s.trim(); }).filter(Boolean)
        : [];

    if (!categoryName) {
        mountEl.innerHTML = '<p style="color:red">Вкажіть атрибут data-category</p>';
        return;
    }

    var isTouch = ('ontouchstart' in window) || (navigator.maxTouchPoints > 0);

    mw.loader.getScript('https://unpkg.com/vue@3/dist/vue.global.prod.js').then(function () {

        var apiBase = mw.config.get('wgScriptPath') + '/api.php';

        function parseInfobox(wikitext) {
            if (!wikitext) return {};
            var fields = {};
            var depth = 0, start = -1, end = -1;
            for (var i = 0; i < wikitext.length; i++) {
                if (wikitext[i] === '{' && wikitext[i + 1] === '{') {
                    if (depth === 0) start = i;
                    depth++;
                    i++;
                } else if (wikitext[i] === '}' && wikitext[i + 1] === '}') {
                    depth--;
                    if (depth === 0) { end = i + 2; break; }
                    i++;
                }
            }
            var box = (start >= 0 && end > start) ? wikitext.substring(start, end) : wikitext;
            var lineRe = /\|\s*([\w\u0400-\u04FF]+)\s*=\s*([^\|\n\}]*)/gi;
            var m;
            while ((m = lineRe.exec(box)) !== null) {
                var key = m[1].trim().toLowerCase();
                if (key === 'class' || key === 'style') continue;
                var val = m[2].trim()
                    .replace(/\[\[(?:[^\|\]]*\|)?([^\]]+)\]\]/g, '$1')
                    .replace(/'{2,3}/g, '')
                    .replace(/<[^>]+>/g, '');
                if (val) fields[key] = val;
            }
            return fields;
        }

        function resolveFilterValue(fields, explicit) {
            if (!explicit || explicit === 'auto') {
                var priority = ['посада', 'position', 'title', 'rank', 'тип', 'type', 'категорія', 'рубрика'];
                for (var i = 0; i < priority.length; i++) {
                    if (fields[priority[i]]) return fields[priority[i]];
                }
                var skip = ['image', 'зображення', 'photo', 'фото'];
                var keys = Object.keys(fields);
                for (var j = 0; j < keys.length; j++) {
                    if (skip.indexOf(keys[j]) === -1) return fields[keys[j]];
                }
                return '';
            }
            return fields[explicit.toLowerCase()] || '';
        }

        function filterLabelFromTitle(pageTitle) {
            if (!fixedFilters.length || !pageTitle) return 'Інше';
            var lower = pageTitle.toLowerCase();
            for (var i = 0; i < fixedFilters.length; i++) {
                if (lower.indexOf(fixedFilters[i].toLowerCase()) !== -1) {
                    return fixedFilters[i];
                }
            }
            return 'Інше';
        }

        function matchFixedFilter(rawVal) {
            if (!fixedFilters.length || !rawVal) return rawVal;
            var lower = rawVal.toLowerCase();
            for (var i = 0; i < fixedFilters.length; i++) {
                if (lower.indexOf(fixedFilters[i].toLowerCase()) !== -1 ||
                    fixedFilters[i].toLowerCase().indexOf(lower) !== -1) {
                    return fixedFilters[i];
                }
            }
            return rawVal;
        }

        function toFilterLabel(val) {
            if (!val) return 'Інше';
            if (fixedFilters.length) return val;
            if (val.length <= 12) return val;
            return val.split(/[\s,]/)[0];
        }

        function sortItems(items) {
            if (!sortOrder.length) {
                return items.slice().sort(function(a, b) {
                    return a.title.localeCompare(b.title, 'uk');
                });
            }
            return items.slice().sort(function(a, b) {
                var ai = sortOrder.indexOf(a.filterLabel);
                var bi = sortOrder.indexOf(b.filterLabel);
                if (ai === -1) ai = sortOrder.length;
                if (bi === -1) bi = sortOrder.length;
                if (ai !== bi) return ai - bi;
                return a.title.localeCompare(b.title, 'uk');
            });
        }

        var app = Vue.createApp({
            data() {
                return {
                    items:        [],
                    loading:      true,
                    error:        null,
                    activeFilter: 'Всі',
                    filters:      ['Всі'],
                    preview:      null,
                    previewX:     0,
                    previewY:     0,
                    previewTimer: null,
                    searchQuery:  '',
                    gridColumns:  columns,
                    isTouch:      isTouch,
                };
            },

            computed: {
                filteredItems() {
                    var vm = this;
                    var q = vm.searchQuery.trim().toLowerCase();
                    var base = vm.items.filter(function (item) {
                        if (!item || !item.title) return false;
                        var matchFilter = vm.activeFilter === 'Всі' || item.filterLabel === vm.activeFilter;
                        var matchSearch = !q ||
                            item.title.toLowerCase().indexOf(q) !== -1 ||
                            (item.description && item.description.toLowerCase().indexOf(q) !== -1);
                        return matchFilter && matchSearch;
                    });
                    return sortItems(base);
                },

                gridStyle() {
                    if (window.innerWidth <= 480) return 'grid-template-columns: 1fr;';
                    return 'grid-template-columns: repeat(' + this.gridColumns + ', 1fr);';
                }
            },

            mounted() {
                this.loadItems();
            },

            methods: {
                showPreview(item, event) {
                    if (this.isTouch || !item) return;
                    var vm = this;
                    clearTimeout(vm.previewTimer);
                    var rect = (event.currentTarget || event.target).getBoundingClientRect();
                    var scrollY = window.scrollY || window.pageYOffset;
                    var scrollX = window.scrollX || window.pageXOffset;
                    vm.previewTimer = setTimeout(function () {
                        var spaceRight = window.innerWidth - rect.right;
                        vm.previewX = spaceRight > 290
                            ? rect.right + scrollX + 12
                            : rect.left + scrollX - 282;
                        vm.previewY = rect.top + scrollY;
                        vm.preview  = item;
                    }, 250);
                },
                hidePreview() {
                    if (this.isTouch) return;
                    clearTimeout(this.previewTimer);
                    this.previewTimer = setTimeout(() => { this.preview = null; }, 150);
                },
                keepPreview() {
                    if (this.isTouch) return;
                    clearTimeout(this.previewTimer);
                },

                async loadItems() {
                    this.loading = true;
                    this.error   = null;
                    try {
                        // ── 1. Збираємо ВСІХ членів категорії через cmcontinue ──
                        var members = [];
                        var continueToken = null;

                        do {
                            var url = apiBase +
                                '?action=query&list=categorymembers' +
                                '&cmtitle=' + encodeURIComponent('Категорія:' + categoryName) +
                                '&cmlimit=500&cmnamespace=0&format=json';

                            if (continueToken) {
                                url += '&cmcontinue=' + encodeURIComponent(continueToken);
                            }

                            var catResp = await fetch(url);
                            var catData = await catResp.json();
                            var batch = (catData.query || {}).categorymembers || [];
                            members = members.concat(batch);

                            continueToken = (catData.continue && catData.continue.cmcontinue)
                                ? catData.continue.cmcontinue
                                : null;

                        } while (continueToken);

                        // Якщо data-limit заданий явно — обрізаємо
                        if (pageLimit && pageLimit < members.length) {
                            members = members.slice(0, pageLimit);
                        }

                        if (!members.length) { this.loading = false; return; }

                        // ── 2. Завантажуємо вміст сторінок батчами по 50 ──
                        var pages = [];
                        var batchSize = 50;

                        for (var offset = 0; offset < members.length; offset += batchSize) {
                            var batchMembers = members.slice(offset, offset + batchSize);
                            var titles = batchMembers.map(function(m) { return m.title; }).join('|');

                            var pageResp = await fetch(
                                apiBase + '?action=query&titles=' + encodeURIComponent(titles) +
                                '&prop=revisions&rvprop=content&format=json'
                            );
                            var pageData = await pageResp.json();
                            var batchPages = Object.values((pageData.query || {}).pages || {});
                            pages = pages.concat(batchPages);
                        }

                        // ── 3. Обробляємо кожну сторінку ──
                        var filterSet = new Set();

                        var promises = pages.map(async function(page) {
                            try {
                                var content = (page.revisions && page.revisions[0])
                                    ? (page.revisions[0]['*'] || '') : '';

                                var filterLabel;

                                if (filterFromTitle) {
                                    filterLabel = filterLabelFromTitle(page.title);
                                } else {
                                    var fields  = parseInfobox(content);
                                    var rawVal  = resolveFilterValue(fields, filterField === 'auto' ? 'auto' : filterField);
                                    var matched = fixedFilters.length ? matchFixedFilter(rawVal) : rawVal;
                                    filterLabel = toFilterLabel(matched);
                                }

                                if (filterLabel && filterLabel !== 'Інше') filterSet.add(filterLabel);

                                var description = extractDescription(content);
                                var imgName     = extractImageName(content);
                                var imgSrc      = null;

                                if (imgName) {
                                    try {
                                        var fileTitle = /^(Файл|File|Image|Зображення):/i.test(imgName)
                                            ? imgName : 'File:' + imgName;
                                        var imgResp = await fetch(
                                            apiBase + '?action=query&titles=' + encodeURIComponent(fileTitle) +
                                            '&prop=imageinfo&iiprop=url&iiurlwidth=200&format=json'
                                        );
                                        var imgData  = await imgResp.json();
                                        var imgPages = Object.values((imgData.query || {}).pages || {});
                                        var ii = imgPages[0] && imgPages[0].imageinfo && imgPages[0].imageinfo[0];
                                        if (ii) imgSrc = ii.thumburl || ii.url;
                                    } catch (e) { /* ignore */ }
                                }

                                var pageUrl = mw.config.get('wgArticlePath').replace(
                                    '$1', encodeURIComponent(page.title.replace(/ /g, '_'))
                                );

                                var extra = [];
                                if (!filterFromTitle) {
                                    var fields2   = parseInfobox(content);
                                    var extraKeys = ['посада', 'position', 'occupation', 'спеціальність',
                                                     'рік', 'рубрика', 'тип', 'автор', 'faculty'];
                                    extraKeys.forEach(function(k) {
                                        if (fields2[k]) extra.push({ label: k, value: fields2[k] });
                                    });
                                }

                                return {
                                    title:       page.title,
                                    filterLabel: filterLabel || 'Інше',
                                    description: description || '',
                                    imgSrc:      imgSrc,
                                    pageUrl:     pageUrl,
                                    extra:       extra.slice(0, 3),
                                };
                            } catch (e) {
                                console.error('[vcc] page error:', e, page && page.title);
                                return null;
                            }
                        });

                        var results = await Promise.all(promises);
                        this.items = results.filter(function(item) { return item != null; });

                        // ── 4. Будуємо список фільтрів ──
                        var builtFilters;
                        if (fixedFilters.length) {
                            var itemsRef = this.items;
                            builtFilters = fixedFilters.filter(function(f) {
                                return itemsRef.some(function(item) { return item.filterLabel === f; });
                            });
                        } else {
                            builtFilters = Array.from(filterSet).sort(function(a, b) {
                                return a.localeCompare(b, 'uk');
                            });
                        }
                        this.filters = ['Всі'].concat(builtFilters);

                    } catch (e) {
                        console.error('[vue-category-cards] error:', e);
                        this.error = 'Не вдалося завантажити дані.';
                    }
                    this.loading = false;
                }
            },

            template: `
<div class="vcc-app">

  <div class="vcc-topbar">
    <input
      class="vcc-search"
      type="text"
      v-model="searchQuery"
      placeholder="Пошук..."
    />
    <span class="vcc-count" v-if="!loading">
      Знайдено: <strong>{{ filteredItems.length }}</strong> з {{ items.length }}
    </span>
  </div>

  <div class="vcc-layout">

    <div class="vcc-main">

      <div class="vcc-loading" v-if="loading">
        <div class="vcc-spinner"></div>
        <span>Завантаження...</span>
      </div>

      <div class="vcc-error" v-else-if="error">{{ error }}</div>

      <div class="vcc-empty" v-else-if="!filteredItems.length">
        <div class="vcc-empty-icon">🔍</div>
        <p>Нічого не знайдено</p>
        <button class="vcc-reset-btn" @click="activeFilter = 'Всі'; searchQuery = ''">
          Скинути фільтри
        </button>
      </div>

      <div class="vcc-grid" :style="gridStyle" v-else>
        <a
          v-for="item in filteredItems"
          :key="item.title"
          :href="item.pageUrl"
          class="vcc-card"
          @mouseenter="showPreview(item, $event)"
          @mouseleave="hidePreview"
        >
          <div class="vcc-card-img-wrap">
            <img v-if="item.imgSrc" :src="item.imgSrc" :alt="item.title" class="vcc-card-img" />
            <div v-else class="vcc-card-img-placeholder">{{ item.title.charAt(0) }}</div>
          </div>
          <div class="vcc-card-body">
            <div v-if="item.filterLabel && item.filterLabel !== 'Інше'"
                 class="vcc-card-badge">{{ item.filterLabel }}</div>
            <div class="vcc-card-name">{{ item.title }}</div>
            <div class="vcc-card-desc" v-if="item.description">{{ item.description }}</div>
          </div>
        </a>
      </div>
    </div>

    <div class="vcc-sidebar" v-if="filters.length > 2">
      <div class="vcc-sidebar-title">Фільтр</div>
      <div class="vcc-filters">
        <button
          v-for="f in filters"
          :key="f"
          class="vcc-filter-btn"
          :class="{ active: activeFilter === f }"
          @click="activeFilter = f"
        >{{ f }}</button>
      </div>
    </div>

  </div>

  <teleport to="body" v-if="!isTouch">
    <a
      v-if="preview && preview.title"
      :href="preview.pageUrl"
      class="vcc-preview"
      :style="{ top: previewY + 'px', left: previewX + 'px' }"
      @mouseenter="keepPreview"
      @mouseleave="hidePreview"
    >
      <div class="vcc-preview-top">
        <img v-if="preview.imgSrc" :src="preview.imgSrc" class="vcc-preview-img" :alt="preview.title" />
        <div v-else class="vcc-preview-img-placeholder">{{ preview.title.charAt(0) }}</div>
        <div class="vcc-preview-info">
          <div class="vcc-preview-badge" v-if="preview.filterLabel && preview.filterLabel !== 'Інше'">
            {{ preview.filterLabel }}
          </div>
          <div class="vcc-preview-name">{{ preview.title }}</div>
        </div>
      </div>
      <div class="vcc-preview-divider"></div>
      <div class="vcc-preview-desc" v-if="preview.description">{{ preview.description }}</div>
      <div class="vcc-preview-row" v-for="e in preview.extra" :key="e.label">
        <span class="vcc-preview-lbl">{{ e.label }}</span>
        <span class="vcc-preview-val">{{ e.value }}</span>
      </div>
    </a>
  </teleport>

</div>
            `
        });

        app.mount('#vue-category-cards');
    });
});

/* ══════════════════════════════════════════════
   ГОЛОВНА СТОРІНКА
══════════════════════════════════════════════ */

function animateNumber(element, target) {
    element.classList.add('animating');
    var current = 0;
    var increment = target / 60;
    var timer = setInterval(function() {
        current += increment;
        if (current >= target) {
            current = target;
            clearInterval(timer);
            setTimeout(function() { element.classList.remove('animating'); }, 100);
        }
        element.textContent = Math.floor(current);
    }, 16);
}

mw.hook('wikipage.content').add(function() {
    if (mw.config.get('wgPageName') !== 'Головна_сторінка') return;

    var statsNumbers = document.querySelectorAll('.stats-panel-number');
    var animated = false;

    function checkAndAnimate() {
        if (animated) return;
        var statsPanel = document.querySelector('.stats-panel');
        if (!statsPanel) return;

        var rect = statsPanel.getBoundingClientRect();
        if (rect.top < window.innerHeight && rect.bottom > 0) {
            animated = true;
            statsNumbers.forEach(function(el) {
                var text = el.textContent.trim();
                var num = parseInt(text.replace(/[^\d]/g, ''), 10);
                if (!isNaN(num) && num > 0) {
                    el.textContent = '0';
                    setTimeout(function() { animateNumber(el, num); }, 200);
                }
            });
        }
    }

    window.addEventListener('scroll', checkAndAnimate);
    checkAndAnimate();
});

mw.hook('wikipage.content').add(function() {
    document.querySelectorAll('div[style*="grid-template-columns"]').forEach(function(grid) {
        var cards = Array.from(grid.children);
        if (cards.length < 2) return;

        cards.sort(function(a, b) {
            var aLink = a.querySelector('div[style*="flex-grow"] a');
            var bLink = b.querySelector('div[style*="flex-grow"] a');
            if (!aLink || !bLink) return 0;

            var aSurname = aLink.textContent.trim().split(' ')[0];
            var bSurname = bLink.textContent.trim().split(' ')[0];

            return aSurname.localeCompare(bSurname, 'uk');
        });

        cards.forEach(function(card) {
            grid.appendChild(card);
        });
    });
});

mw.hook('wikipage.content').add(function() {
    if (mw.config.get('wgPageName') !== 'Головна_сторінка') return;

    var progressBar = document.createElement('div');
    progressBar.className = 'scroll-progress';
    document.body.appendChild(progressBar);

    function updateProgress() {
        var winScroll = document.documentElement.scrollTop || document.body.scrollTop;
        var height = document.documentElement.scrollHeight - document.documentElement.clientHeight;
        if (height <= 0) return;
        var scrolled = (winScroll / height) * 100;
        progressBar.style.width = scrolled + '%';
    }

    window.addEventListener('scroll', updateProgress, { passive: true });
    updateProgress();
});

mw.hook('wikipage.content').add(function() {
    if (mw.config.get('wgPageName') !== 'Головна_сторінка') return;

    var welcomeWrapper = document.querySelector('.welcome-wrapper');
    if (!welcomeWrapper) return;

    if (window.innerWidth < 768) return;
    if (window.matchMedia('(prefers-reduced-motion: reduce)').matches) return;

    var canvas = document.createElement('canvas');
    canvas.className = 'particles-canvas';
    canvas.style.cssText = 'position:absolute;top:0;left:0;width:100%;height:100%;pointer-events:none;z-index:0;';

    canvas.style.webkitMaskImage = 'linear-gradient(to bottom, rgba(0,0,0,0) 0%, rgba(0,0,0,1) 10%, rgba(0,0,0,1) 90%, rgba(0,0,0,0) 100%), linear-gradient(to right, rgba(0,0,0,0) 0%, rgba(0,0,0,1) 10%, rgba(0,0,0,1) 90%, rgba(0,0,0,0) 100%)';
    canvas.style.maskImage = 'linear-gradient(to bottom, rgba(0,0,0,0) 0%, rgba(0,0,0,1) 10%, rgba(0,0,0,1) 90%, rgba(0,0,0,0) 100%), linear-gradient(to right, rgba(0,0,0,0) 0%, rgba(0,0,0,1) 10%, rgba(0,0,0,1) 90%, rgba(0,0,0,0) 100%)';
    canvas.style.webkitMaskComposite = 'source-in';
    canvas.style.maskComposite = 'intersect';
    welcomeWrapper.style.position = 'relative';
    welcomeWrapper.insertBefore(canvas, welcomeWrapper.firstChild);

    var ctx = canvas.getContext('2d');
    canvas.width = welcomeWrapper.offsetWidth;
    canvas.height = welcomeWrapper.offsetHeight;

    var particles = [];
    var particleCount = 40;
    var animId;

    function Particle() {
        this.x = Math.random() * canvas.width;
        this.y = Math.random() * canvas.height;
        this.vx = (Math.random() - 0.5) * 0.5;
        this.vy = (Math.random() - 0.5) * 0.5;
        this.radius = Math.random() * 2 + 1;
    }

    Particle.prototype.draw = function() {
        ctx.beginPath();
        ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2);
        ctx.fillStyle = 'rgba(255, 215, 0, 0.6)';
        ctx.fill();
    };

    Particle.prototype.update = function() {
        if (this.x > canvas.width || this.x < 0) this.vx = -this.vx;
        if (this.y > canvas.height || this.y < 0) this.vy = -this.vy;
        this.x += this.vx;
        this.y += this.vy;
        this.draw();
    };

    for (var i = 0; i < particleCount; i++) {
        particles.push(new Particle());
    }

    function animate() {
        ctx.clearRect(0, 0, canvas.width, canvas.height);

        for (var i = 0; i < particles.length; i++) {
            particles[i].update();
            for (var j = i + 1; j < particles.length; j++) {
                var dx = particles[i].x - particles[j].x;
                var dy = particles[i].y - particles[j].y;
                var distance = Math.sqrt(dx * dx + dy * dy);

                if (distance < 120) {
                    ctx.beginPath();
                    ctx.strokeStyle = 'rgba(255, 215, 0, ' + (1 - distance / 120) * 0.3 + ')';
                    ctx.lineWidth = 1;
                    ctx.moveTo(particles[i].x, particles[i].y);
                    ctx.lineTo(particles[j].x, particles[j].y);
                    ctx.stroke();
                }
            }
        }

        animId = requestAnimationFrame(animate);
    }

    animate();

    var resizeTimer;
    window.addEventListener('resize', function() {
        clearTimeout(resizeTimer);
        resizeTimer = setTimeout(function() {
            canvas.width = welcomeWrapper.offsetWidth;
            canvas.height = welcomeWrapper.offsetHeight;
            if (window.innerWidth < 768) {
                cancelAnimationFrame(animId);
                canvas.remove();
            }
        }, 200);
    });
});