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

Матеріал з Київський національний лінгвістичний університет
Перейти до навігації Перейти до пошуку
Немає опису редагування
Немає опису редагування
Мітка: Скасовано
Рядок 1: Рядок 1:
/* ════════════════════════════════════
// Виправляємо viewport
  ГЛОБАЛЬНИЙ ФІКС ГОРИЗОНТАЛЬНОГО СКРОЛУ
(function() {
═══════════════════════════════════════ */
    var viewport = document.querySelector('meta[name="viewport"]');
html {
    if (viewport) {
    overflow-x: hidden;
        viewport.setAttribute('content', 'width=device-width, initial-scale=1.0, maximum-scale=5.0, viewport-fit=cover');
     width: 100%;
     } 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);
    }
})();


body {
$(function() {
     overflow-x: hidden;
     $('.category-card').each(function() {
    width: 100%;
        var $card = $(this);
    max-width: 100vw;
        var href = $card.attr('data-href');
     position: relative;
       
}
        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'); }
            );
        }
     });
});


/* Контейнери MediaWiki не повинні виходити за межі */
/* ══════════════════════════════════════════════
#mw-page-base,
  МОБІЛЬНА ШАПКА + НИЖНІЙ ТАББАР
#mw-head-base,
══════════════════════════════════════════════ */
#mw-head,
#mw-panel,
#content,
.mw-body,
.mw-page-container,
.mw-page-container-inner,
.mw-content-container,
#bodyContent,
#mw-content-text,
.mw-parser-output {
    max-width: 100% !important;
    box-sizing: border-box !important;
    overflow-x: hidden !important;
}


/* Блочні елементи не виходять за межі екрану */
mw.hook('wikipage.content').add(function() {
div, section, article, aside, nav, header, footer, main,
p, ul, ol, li, table, form, fieldset, blockquote, pre {
    max-width: 100%;
    box-sizing: border-box;
}


/* ── Заголовок сторінки ── */
    /* ── Оверлей ── */
#firstHeading {
    var overlay = document.createElement('div');
     font-size: clamp(28px, 4vw, 48px);
     overlay.className = 'mobile-menu-overlay';
}
    document.body.appendChild(overlay);


/* ── Бокове меню ── */
    /* ── Мобільна шапка ── */
#mw-panel {
     var topbar = document.createElement('div');
     font-size: clamp(14px, 1.2vw, 18px);
    topbar.className = 'mobile-topbar';
}


/* ── Прибираємо обмеження Vector ── */
    // Визначаємо URL логотипа та головної сторінки
body.skin-vector-2022 .mw-page-container-inner,
    var wikiLogo = document.querySelector('#p-logo img, .mw-wiki-logo img, img.mw-logo-icon, #p-logo a, .mw-logo img');
body.skin-vector .mw-content-container,
    var logoSrc = '';
body.skin-vector .vector-body,
    if (wikiLogo && wikiLogo.tagName === 'IMG') {
body.skin-vector #bodyContent {
        logoSrc = wikiLogo.src;
     max-width: none !important;
     } else if (wikiLogo && wikiLogo.tagName === 'A') {
     padding-left: 0 !important;
        var bgStyle = window.getComputedStyle(wikiLogo).backgroundImage;
     padding-right: 0 !important;
        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');


body.skin-vector-2022 .mw-body,
    var logoHtml = logoSrc
body.skin-vector-2022 .mw-body-content {
        ? '<img src="' + logoSrc + '" alt="Логотип" style="max-width:32px!important;width:32px;height:32px;">'
    max-width: none !important;
        : '<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>';
    margin: 0 !important;
}


/* ════════════════════════════════════
    // Юзер-аватар: перша літера імені або іконка
  ПРИВІТАННЯ + СТАТИСТИКА
     var userInitial = isLoggedIn ? (userName.charAt(0).toUpperCase()) : '';
═══════════════════════════════════════ */
     var userAvatarHtml = isLoggedIn
.welcome-wrapper {
        ? '<span class="topbar-user-avatar" aria-label="' + mw.html.escape(userName) + '">' + mw.html.escape(userInitial) + '</span>'
     display: flex;
        : '<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>';
     align-items: center;
    justify-content: space-between;
    gap: 40px;
    padding: 40px 5vw 40px;
    box-sizing: border-box;
    width: 100%;
}


.welcome-text {
    // Дропдаун для залогіненого юзера
    flex: 1;
    var dropdownHtml = isLoggedIn
    text-align: center;
        ? '<div class="topbar-user-dropdown" id="topbar-user-dropdown">' +
    transform: translateX(-50px);
            '<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>'
        : '';


.welcome-subtitle {
    topbar.innerHTML =
    font-family: system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
        // Кнопка відкриття сайдбара
    font-size: 1.45rem;
        '<button class="topbar-menu-btn" id="topbar-menu-btn" aria-label="Меню">' +
    font-weight: 400;
            '<span class="topbar-hamburger"><span></span><span></span><span></span></span>' +
    color: #444;
        '</button>' +
    letter-spacing: 0.6px;
        // Логотип + назва
    margin-bottom: 10px;
        '<a class="mobile-topbar-logo" href="' + mainPageUrl + '" aria-label="На головну">' +
    opacity: 0.92;
            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>';


.welcome-title {
    document.body.insertBefore(topbar, document.body.firstChild);
    font-family: system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
    font-size: 2.45rem;
    font-weight: 700;
    line-height: 1.18;
    color: #003d82;
    letter-spacing: -0.3px;
    margin: 0;
}


/* ── Панель статистики ── */
    // Переміщуємо рідний пошуковий блок MediaWiki у топбар
.stats-panel {
    var nativeSearch = document.getElementById('p-search');
    width: 260px;
     if (!nativeSearch) nativeSearch = document.getElementById('searchform');
     flex-shrink: 0;
     if (!nativeSearch) nativeSearch = document.querySelector('form[action*="search"]');
     background: white;
     var searchSlot = document.getElementById('mobile-topbar-search-slot');
     border-radius: 16px;
     if (nativeSearch && searchSlot) {
     border: 1px solid rgba(0,61,130,0.08);
        searchSlot.appendChild(nativeSearch);
    box-shadow: 0 6px 24px rgba(0,0,0,0.07);
     }
     overflow: hidden;
}


.stats-panel-header {
     // Дропдаун юзера — position:fixed, завжди правий край
     background: rgba(210, 230, 255, 0.35);
    var userWrap = topbar.querySelector('#topbar-user-wrap');
     color: #003d82;
     var userDropdown = topbar.querySelector('#topbar-user-dropdown');
     font-family: system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
     if (userWrap && userDropdown) {
    font-size: 1rem;
        userWrap.addEventListener('click', function(e) {
    font-weight: 700;
            e.stopPropagation();
    padding: 12px 18px;
            var isOpen = userDropdown.classList.contains('open');
    border-bottom: 1px solid rgba(0,61,130,0.1);
            userDropdown.classList.toggle('open', !isOpen);
}
        });
        document.addEventListener('click', function() {
            userDropdown.classList.remove('open');
        });
    }


.stats-panel-list {
    /* ── Логіка відкриття/закриття бокового меню ── */
    padding: 4px 0;
    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');
    }


.stats-panel-item {
    function closeMenu() {
    display: flex;
        document.body.classList.remove('mobile-nav-open');
    justify-content: space-between;
        overlay.classList.remove('open');
    align-items: center;
        var menuBtn = topbar.querySelector('#topbar-menu-btn');
    padding: 10px 18px;
        if (menuBtn) menuBtn.classList.remove('active');
    border-bottom: 1px solid rgba(0,61,130,0.05);
     }
     transition: background 0.2s;
}


.stats-panel-item:last-child {
    var topbarMenuBtn = topbar.querySelector('#topbar-menu-btn');
    border-bottom: none;
    if (topbarMenuBtn) {
}
        topbarMenuBtn.addEventListener('click', function(e) {
            e.stopPropagation();
            if (document.body.classList.contains('mobile-nav-open')) {
                closeMenu();
            } else {
                openMenu();
            }
        });
    }


.stats-panel-item:hover {
    overlay.addEventListener('click', closeMenu);
    background: rgba(210, 230, 255, 0.2);
}


.stats-panel-label {
    document.addEventListener('keydown', function(e) {
    font-family: system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
        if (e.key === 'Escape') closeMenu();
     font-size: 14px;
     });
    color: #555;
}


.stats-panel-number {
    window.addEventListener('resize', function() {
    font-family: system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
        if (window.innerWidth > 1100) closeMenu();
    font-size: 18px;
     });
     font-weight: 800;
});
    color: #003d82;
}


/* ════════════════════════════════════
  ЗАГОЛОВОК КАТЕГОРІЙ
═══════════════════════════════════════ */
.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;
    background: transparent;
    box-sizing: border-box;
    margin-right: calc(360px + 24px);
}


.section-categories::after {
/* ══════════════════════════════════════════════
    content: '';
  МОБІЛЬНИЙ ФІК РОЗМІРУ THUMB-КАРТИНОК
    display: block;
  CSS не може перебити inline style="width:Npx" від MediaWiki,
    width: 90px;
  тому знімаємо його через JS на мобільних
    height: 4px;
══════════════════════════════════════════════ */
     background: #ffd700;
mw.hook('wikipage.content').add(function() {
    margin: 14px auto 0;
     function fixThumbWidths() {
    border-radius: 2px;
        if (window.innerWidth > 1100) return;
}


/* ════════════════════════════════════
        var vw = window.innerWidth;
  ОСНОВНИЙ LAYOUT: категорії + права колонка
        // clamp(120, 48vw, 280) — та сама формула що в CSS
═══════════════════════════════════════ */
        var targetWidth = Math.min(280, Math.max(120, Math.round(vw * 0.48)));
.main-content-layout {
    display: flex;
    gap: 24px;
    align-items: flex-start;
    padding: 0 5vw;
    margin: 0 0 70px;
    box-sizing: border-box;
    width: 100%;
}


/* ── Ліва колонка з заголовком і сіткою ── */
        // .thumbinner — основний контейнер з inline style="width:Npx"
.category-column {
        document.querySelectorAll('.mw-parser-output .thumbinner').forEach(function(el) {
    flex: 1;
            el.style.removeProperty('width');
    min-width: 0;
            el.style.setProperty('width', targetWidth + 'px', 'important');
    display: flex;
            el.style.setProperty('max-width', '100%', 'important');
    flex-direction: column;
            el.style.setProperty('box-sizing', 'border-box', 'important');
}
        });


/* ── Сітка карток 3 в ряд ── */
        // img всередині thumb на всю ширину контейнера
.category-grid-container {
        document.querySelectorAll('.mw-parser-output .thumbinner img').forEach(function(el) {
    display: grid;
            el.style.setProperty('width', '100%', 'important');
    grid-template-columns: repeat(3, 1fr);
            el.style.setProperty('max-width', '100%', 'important');
    gap: 20px;
            el.style.setProperty('height', 'auto', 'important');
    flex: 1;
        });
     min-width: 0;
     }
}


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


/* ════════════════════════════════════
    window.addEventListener('resize', fixThumbWidths, { passive: true });
  КАРТКИ КАТЕГОРІЙ
});
═══════════════════════════════════════ */
.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 {
    transform: translateY(-6px);
    box-shadow: 0 20px 40px rgba(0,61,130,0.18);
    border-color: rgba(0,61,130,0.15);
}


.card-image {
    padding: 20px 0 12px;
    flex-grow: 1;
    display: flex;
    align-items: center;
    justify-content: center;
    background: white;
}


.card-image img {
    width: 230px;
    height: 230px;
    object-fit: contain;
    transition: transform 0.35s ease;
}


.category-card:hover .card-image img {
/* ══════════════════════════════════════════════
     transform: scale(1.12);
  ГЛОБАЛЬНІ ПАРСЕРИ
══════════════════════════════════════════════ */
    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;
}
}


.card-title {
function extractDescription(wikitext) {
     font-size: 15px;
     if (!wikitext) return '';
    font-weight: 600;
     var text = wikitext;
    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 {
    var depth = 0, end = -1;
    background: transparent !important;
     for (var i = 0; i < text.length; i++) {
     border: none !important;
        if (text[i] === '{' && text[i + 1] === '{') { depth++; i++; }
    box-shadow: none !important;
        else if (text[i] === '}' && text[i + 1] === '}') {
    padding: 0 !important;
            depth--;
    margin: 0 !important;
            if (depth === 0) { end = i + 2; break; }
    font-family: system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
            i++;
    font-size: inherit !important;
        }
    font-weight: inherit !important;
     }
     color: inherit !important;
     if (end > 0) text = text.substring(end);
     white-space: normal !important;
}


/* ════════════════════════════════════
    text = text
  ВИПАДКОВІ СТАТТІ
        .replace(/\[\[(?:Файл|File|Зображення|Image):[^\]]*\]\]/gi, '')
═══════════════════════════════════════ */
        .replace(/\{\|[\s\S]*?\|\}/g, '')
.random-articles-panel {
        .replace(/\{\{[^}]*\}\}/g, '')
    background: white;
        .replace(/={2,6}[^=\n]+=+/g, '')
    border-radius: 16px;
        .replace(/\[\[(?:[^\|\]]*\|)?([^\]]+)\]\]/g, '$1')
    border: 1px solid rgba(0,61,130,0.08);
        .replace(/\[[^\s\]]+\s+([^\]]+)\]/g, '$1')
    box-shadow: 0 6px 24px rgba(0,0,0,0.07);
        .replace(/\[[^\]]+\]/g, '')
    overflow: hidden;
        .replace(/'{2,3}/g, '')
    display: flex;
        .replace(/<[^>]+>/g, '')
    flex-direction: column;
        .replace(/^[\*#:;].*/gm, '');
    position: relative;
}


.random-articles-header {
    var lines = text.split('\n')
    background: rgba(210, 230, 255, 0.35);
        .map(function (l) { return l.trim(); })
    color: #003d82;
        .filter(function (l) { return l.length > 20; });
    font-family: system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
    font-size: 1rem;
    font-weight: 700;
    padding: 14px 18px;
    border-bottom: 1px solid rgba(0,61,130,0.1);
}


#random-articles-list {
     if (!lines.length) return '';
     padding: 12px;
     var result = lines[0].substring(0, 160);
     display: flex;
     return lines[0].length > 160 ? result + '…' : result;
    flex-direction: column;
     gap: 12px;
}
}


.random-article-card {
/* ══════════════════════════════════════════════
    display: flex;
   ВИПАДКОВІ СТАТТІ
    gap: 14px;
══════════════════════════════════════════════ */
    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 {
    background: rgba(210, 230, 255, 0.35);
    border-color: rgba(0,61,130,0.18);
    transform: translateX(3px);
    text-decoration: none;
}
 
.random-article-thumb-wrap {
    width: 90px;
    height: 90px;
    min-width: 90px;
    min-height: 90px;
    border-radius: 10px;
    flex-shrink: 0;
    overflow: hidden;
    background: #eef2f8;
}
 
.random-article-thumb {
    width: 100%;
    height: 100%;
    object-fit: cover;
    object-position: center top;
    display: block;
}
 
.random-article-thumb-placeholder {
    width: 90px;
    height: 90px;
    border-radius: 10px;
    flex-shrink: 0;
    background: linear-gradient(135deg, #e8eef7, #c8d8ee);
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 22px;
}
 
.random-article-info {
    flex: 1;
    min-width: 0;
}
 
.random-article-title {
    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 {
    font-family: system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
    font-size: 13px;
    color: #555;
    line-height: 1.45;
    overflow: hidden;
    display: -webkit-box;
    -webkit-line-clamp: 3;
    -webkit-box-orient: vertical;
}
 
.random-articles-loading {
    padding: 20px;
    text-align: center;
    color: #888;
    font-size: 13px;
    font-family: system-ui, sans-serif;
}
 
.random-articles-refresh {
    display: none;
}
 
/* ════════════════════════════════════
  РЕСУРСИ ТА ПОСИЛАННЯ
═══════════════════════════════════════ */
.resources-and-contacts {
    display: flex;
    flex-wrap: wrap;
    gap: 24px;
    margin: 50px 5vw 60px;
    align-items: stretch;
}
 
.resource-block,
.contacts-block {
    flex: 1;
    min-width: 300px;
    background: linear-gradient(135deg, rgba(255, 255, 255, 0.9), rgba(240, 246, 255, 0.85));
    backdrop-filter: blur(12px);
    -webkit-backdrop-filter: blur(12px);
    border: 1px solid rgba(0, 61, 130, 0.12);
    border-radius: 16px;
    padding: 24px 28px 28px;
    box-shadow: 0 6px 20px rgba(0, 61, 130, 0.08);
    box-sizing: border-box;
    display: flex;
    flex-direction: column;
    transition: all 0.3s cubic-bezier(0.165, 0.84, 0.44, 1);
    position: relative;
    overflow: hidden;
}
 
.resource-block::before,
.contacts-block::before {
    content: '';
    position: absolute;
    top: -50%;
    left: -50%;
    width: 200%;
    height: 200%;
    background: linear-gradient(135deg, transparent, rgba(0, 61, 130, 0.04), transparent);
    transform: rotate(45deg);
    transition: all 0.6s ease;
    opacity: 0;
}
 
.resource-block:hover,
.contacts-block:hover {
    transform: translateY(-6px);
    box-shadow: 0 12px 32px rgba(0, 61, 130, 0.14);
    border-color: rgba(0, 61, 130, 0.18);
}
 
.resource-block:hover::before,
.contacts-block:hover::before {
    opacity: 1;
    top: -25%;
    left: -25%;
}
 
.resource-block ul,
.contacts-block ul {
    flex: 1;
    list-style: none;
    padding-left: 0;
    margin: 0;
    position: relative;
    z-index: 1;
}
 
.resource-block h2,
.contacts-block h2 {
    font-family: system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif !important;
    font-size: 1.4rem !important;
    font-weight: 700 !important;
    color: #003d82 !important;
    margin: 0 0 18px 0 !important;
    padding: 0 0 12px 0 !important;
    line-height: 1.3 !important;
    letter-spacing: -0.3px !important;
    position: relative;
    z-index: 1;
}
 
.resource-block li,
.contacts-block li {
    margin-bottom: 10px;
    line-height: 1.6;
    font-size: 14.5px;
    color: #444;
    padding: 8px 12px 8px 28px;
    position: relative;
    border-radius: 8px;
    transition: all 0.2s ease;
    background: rgba(255, 255, 255, 0.4);
}
 
.resource-block li:hover,
.contacts-block li:hover {
    background: rgba(0, 61, 130, 0.06);
    transform: translateX(4px);
}
 
.resource-block li::before,
.contacts-block li::before {
    content: '→';
    position: absolute;
    left: 10px;
    color: #003d82;
    font-weight: 700;
    font-size: 16px;
    transition: transform 0.2s;
}
 
.resource-block li:hover::before,
.contacts-block li:hover::before {
    transform: translateX(3px);
}
 
.resource-block li a,
.contacts-block li a {
    color: #0645ad;
    text-decoration: none;
    transition: color 0.2s;
    font-weight: 500;
}
 
.resource-block li a:hover,
.contacts-block li a:hover {
    color: #003d82;
    text-decoration: none;
}
 
/* ════════════════════════════════════
   MODERN UI: градієнти, glassmorphism, анімації
══════════════════════════════════════ */
 
/* ── Прогрес скролла ── */
.scroll-progress {
    position: fixed;
    top: 0;
    left: 0;
    height: 4px;
    background: linear-gradient(90deg, #003d82, #0066cc, #ffd700);
    z-index: 99999;
    transition: width 0.1s ease;
    box-shadow: 0 2px 8px rgba(0, 61, 130, 0.3);
}
 
/* ── Градієнтний фон для welcome ── */
.welcome-wrapper {
    background: linear-gradient(135deg, #f0f6ff 0%, #e8f0ff 50%, #fff 100%);
    position: relative;
    overflow: hidden;
}
 
.welcome-wrapper::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background:
        linear-gradient(to bottom, white 0%, transparent 15%, transparent 85%, white 100%),
        linear-gradient(to right, white 0%, transparent 10%, transparent 90%, white 100%);
    pointer-events: none;
    z-index: 10;
}
 
.welcome-text,
.stats-panel {
    position: relative;
    z-index: 11;
}
 
/* ── Glassmorphism для статистики ── */
.stats-panel {
    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 {
    background: linear-gradient(135deg, rgba(0, 61, 130, 0.1), rgba(0, 102, 204, 0.15)) !important;
}
 
/* ── Glassmorphism для випадкових статей ── */
.random-articles-panel {
    background: rgba(255, 255, 255, 0.75) !important;
    backdrop-filter: blur(12px);
    -webkit-backdrop-filter: blur(12px);
    border: 1px solid rgba(255, 255, 255, 0.3) !important;
}
 
/* ── Gradient category cards ── */
.category-card {
    background: linear-gradient(135deg, #ffffff 0%, #f8fbff 100%);
    border: 1px solid rgba(0, 61, 130, 0.08);
    position: relative;
    overflow: hidden;
}
 
.category-card::before {
    content: '';
    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 {
    opacity: 1;
    top: -25%;
    left: -25%;
}
 
.category-card:hover .card-image img {
    animation: icon-bounce 0.6s ease;
}
 
@keyframes icon-bounce {
    0%, 100% { transform: scale(1.12) translateY(0); }
    50% { transform: scale(1.12) translateY(-8px); }
}
 
.category-card {
    transition: all 0.4s cubic-bezier(0.165, 0.84, 0.44, 1);
}
 
.category-card:hover {
    transform: translateY(-8px) scale(1.02);
    box-shadow: 0 24px 48px rgba(0, 61, 130, 0.2);
}
 
@keyframes rainbow {
    0% { color: #003d82; }
    25% { color: #0066cc; }
    50% { color: #4a90e2; }
    75% { color: #0066cc; }
    100% { color: #003d82; }
}
 
.stats-panel-number.animating {
    animation: rainbow 1.5s ease-in-out;
}
 
/* ── Gradient title ── */
.welcome-title {
    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 {
    0%, 100% { background-position: 0% 50%; }
    50% { background-position: 100% 50%; }
}
 
/* ── Neomorphism for random articles ── */
.random-article-card {
    background: linear-gradient(145deg, #ffffff, #f0f6ff);
    box-shadow:
        8px 8px 16px rgba(0, 61, 130, 0.08),
        -8px -8px 16px rgba(255, 255, 255, 0.9);
    border: none !important;
}
 
.random-article-card:hover {
    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);
}
 
.section-categories {
    text-shadow: 0 2px 8px rgba(0, 61, 130, 0.1);
}
 
.section-categories::after {
    background: linear-gradient(90deg, #ffd700, #ffed4e, #ffd700) !important;
    box-shadow: 0 2px 8px rgba(255, 215, 0, 0.4);
}
 
/* ════════════════════════════════════
  БОКОВЕ МЕНЮ
═══════════════════════════════════════ */
 
body #mw-panel,
.mw-body #mw-panel {
    background: transparent !important;
    padding: 0 !important;
    margin-left: 0px !important;
    margin-right: 15px !important;
}
 
body #mw-panel .portal,
.mw-body #mw-panel .portal {
    background: linear-gradient(135deg, rgba(255, 255, 255, 0.9), rgba(240, 246, 255, 0.85)) !important;
    backdrop-filter: blur(12px) !important;
    -webkit-backdrop-filter: blur(12px) !important;
    border-radius: 16px !important;
    padding: 16px 14px 14px !important;
    margin-bottom: 12px !important;
    border: 1px solid rgba(0, 61, 130, 0.12) !important;
    box-shadow: 0 6px 20px rgba(0, 61, 130, 0.08) !important;
    transition: all 0.3s cubic-bezier(0.165, 0.84, 0.44, 1) !important;
    position: relative !important;
    overflow: hidden !important;
}
 
body #mw-panel .portal::before,
.mw-body #mw-panel .portal::before {
    content: '' !important;
    position: absolute !important;
    top: -50% !important;
    left: -50% !important;
    width: 200% !important;
    height: 200% !important;
    background: linear-gradient(135deg, transparent, rgba(0, 61, 130, 0.04), transparent) !important;
    transform: rotate(45deg) !important;
    transition: all 0.6s ease !important;
    opacity: 0 !important;
    pointer-events: none !important;
}
 
body #mw-panel .portal:hover,
.mw-body #mw-panel .portal:hover {
    transform: translateY(-4px) !important;
    box-shadow: 0 10px 28px rgba(0, 61, 130, 0.12) !important;
    border-color: rgba(0, 61, 130, 0.18) !important;
}
 
body #mw-panel .portal:hover::before,
.mw-body #mw-panel .portal:hover::before {
    opacity: 1 !important;
    top: -25% !important;
    left: -25% !important;
}
 
body #mw-panel .portal:last-child,
.mw-body #mw-panel .portal:last-child {
    margin-bottom: 0 !important;
}
 
body #mw-panel .portal h3,
.mw-body #mw-panel .portal h3 {
    font-family: system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif !important;
    font-size: 15px !important;
    font-weight: 700 !important;
    color: #003d82 !important;
    margin: 0 0 12px 0 !important;
    padding: 0 0 10px 0 !important;
    border-bottom: 2px solid rgba(0, 61, 130, 0.15) !important;
    letter-spacing: -0.2px !important;
    line-height: 1.3 !important;
    position: relative !important;
    z-index: 1 !important;
}
 
body #mw-panel .portal .body ul,
.mw-body #mw-panel .portal .body ul {
    margin: 0 !important;
    padding: 0 !important;
    position: relative !important;
    z-index: 1 !important;
}
 
body #mw-panel .portal .body ul li,
.mw-body #mw-panel .portal .body ul li {
    list-style: none !important;
    margin: 0 0 6px 0 !important;
    padding: 0 !important;
}
 
body #mw-panel .portal .body ul li:last-child,
.mw-body #mw-panel .portal .body ul li:last-child {
    margin-bottom: 0 !important;
}
 
body #mw-panel .portal .body ul li a,
.mw-body #mw-panel .portal .body ul li a {
    font-family: system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif !important;
    font-size: 13.5px !important;
    font-weight: 400 !important;
    color: #0645ad !important;
    text-decoration: none !important;
    transition: all 0.2s ease !important;
    display: block !important;
    padding: 9px 12px !important;
    border-radius: 8px !important;
    line-height: 1.4 !important;
    background: rgba(255, 255, 255, 0.4) !important;
    border: 1px solid rgba(0, 61, 130, 0.08) !important;
    box-sizing: border-box !important;
}
 
body #mw-panel .portal .body ul li a:hover,
.mw-body #mw-panel .portal .body ul li a:hover {
    background: rgba(0, 61, 130, 0.06) !important;
    color: #003d82 !important;
    transform: translateX(4px) !important;
    border-color: rgba(0, 61, 130, 0.15) !important;
}
 
body #mw-panel #p-navigation h3,
.mw-body #mw-panel #p-navigation h3 {
    display: block !important;
    visibility: visible !important;
}
 
body #mw-panel #p-navigation .body ul li:first-child,
.mw-body #mw-panel #p-navigation .body ul li:first-child {
    margin: 0 0 12px 0 !important;
}
 
body #mw-panel #p-navigation .body ul li:first-child a,
.mw-body #mw-panel #p-navigation .body ul li:first-child a {
    font-size: 15px !important;
    font-weight: 700 !important;
    color: #003d82 !important;
    padding: 0 0 10px 0 !important;
    border-bottom: 2px solid rgba(0, 61, 130, 0.15) !important;
    background: transparent !important;
    border-left: none !important;
    border-right: none !important;
    border-top: none !important;
    border-radius: 0 !important;
    pointer-events: none !important;
    cursor: default !important;
}
 
body #mw-panel #p-navigation .body ul li:first-child a:hover,
.mw-body #mw-panel #p-navigation .body ul li:first-child a:hover {
    transform: none !important;
}
 
/* ════════════════════════════════════
  ВЕРХНЯ ПАНЕЛЬ
═══════════════════════════════════════ */
 
#mw-page-base {
    background: transparent !important;
    background-image: none !important;
}
 
#mw-head-base {
    background: linear-gradient(135deg, rgba(255, 255, 255, 0.95), rgba(240, 246, 255, 0.9)) !important;
    backdrop-filter: blur(20px) !important;
    -webkit-backdrop-filter: blur(20px) !important;
    border-bottom: 1px solid rgba(0, 61, 130, 0.12) !important;
    box-shadow: 0 2px 12px rgba(0, 61, 130, 0.08) !important;
}
 
#p-personal {
    background: transparent !important;
    border: none !important;
}
 
#p-personal ul {
    display: flex !important;
    align-items: center !important;
    gap: 0 !important;
    background: linear-gradient(135deg, rgba(255,255,255,0.85), rgba(240,246,255,0.75)) !important;
    backdrop-filter: blur(12px) !important;
    -webkit-backdrop-filter: blur(12px) !important;
    border: 1px solid rgba(0, 61, 130, 0.12) !important;
    border-radius: 12px !important;
    padding: 2px 4px !important;
    box-shadow: 0 2px 8px rgba(0, 61, 130, 0.06) !important;
    flex-wrap: nowrap !important;
    white-space: nowrap !important;
    margin-left: 0 !important;
}
 
#p-personal li {
    list-style: none !important;
    margin: 0 !important;
    padding: 0 !important;
}
 
#p-personal li a {
    display: block !important;
    color: #0645ad !important;
    font-family: system-ui, -apple-system, sans-serif !important;
    font-size: 13.5px !important;
    font-weight: 500 !important;
    padding: 6px 10px !important;
    border-radius: 8px !important;
    transition: all 0.15s ease !important;
}
 
#p-personal li a:hover {
    background-color: rgba(0, 61, 130, 0.1) !important;
}


#p-personal li.selected a,
function loadRandomArticles() {
#p-personal li a.mw-ui-button-primary {
     var list = document.getElementById('random-articles-list');
     background: linear-gradient(to right, rgba(240,246,255,0.5), rgba(210,230,255,0.4)) !important;
     if (!list) return;
     color: #003d82 !important;
    font-weight: 600 !important;
}


/* Ховаємо менш важливі пункти щоб рядок не переносився */
    list.innerHTML = '<div class="random-articles-loading">Завантаження...</div>';
#p-personal li#pt-watchlist,
#p-personal li#pt-mycontris {
    display: none !important;
}


#p-personal li a {
     var apiBase = mw.config.get('wgScriptPath') + '/api.php';
     font-size: 12.5px !important;
     var excludedPages = [
     padding: 5px 7px !important;
        'Головна сторінка',
     white-space: nowrap !important;
        'Структурні підрозділи',
}
        'Викладачі',
        'Історія університету',
        'Керівництво університету',
        'Факультети і кафедри',
        'Освітні програми',
        'Сертифікатні програми',
        'Періодичні видання',
        'Наукові конференції',
        'Видатні випускники',
        'Історичні постаті',
        'Корпоративна культура'
     ];


#p-personal li#pt-userpage {
    fetch(apiBase + '?action=query&list=random&rnnamespace=0&rnlimit=10&format=json')
    display: flex !important;
        .then(function(r) { return r.json(); })
    align-items: center !important;
        .then(function(data) {
}
            var pages = data.query.random.filter(function(p) {
                return excludedPages.indexOf(p.title) === -1;
            }).slice(0, 3);


#p-personal li#pt-userpage .mw-userlink {
            var titles = pages.map(function(p) { return p.title; }).join('|');
    display: flex !important;
    align-items: center !important;
    gap: 6px !important;
}


#p-personal li#pt-userpage > a {
            return fetch(
    padding-left: 22px !important;
                apiBase +
    background-position: 4px center !important;
                '?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 = '';


#p-namespaces li,
            var promises = pages.map(function(page) {
#p-views li {
                var title = page.title;
    background: transparent !important;
                var pageUrl = mw.config.get('wgArticlePath').replace(
    border: none !important;
                    '$1', encodeURIComponent(title.replace(/ /g, '_'))
    border-radius: 0 !important;
                );
    margin-right: 8px !important;
    margin-bottom: 0 !important;
    padding: 0 !important;
}


#p-namespaces li a,
                var content = '';
#p-views li a {
                if (page.revisions && page.revisions[0]) {
    color: #0645ad !important;
                    content = page.revisions[0]['*'] || '';
    font-family: system-ui, -apple-system, sans-serif !important;
                }
    font-size: 13.5px !important;
    font-weight: 500 !important;
}


#p-namespaces li.selected,
                var excerpt = extractDescription(content);
#p-views li.selected {
                if (!excerpt) excerpt = 'Немає опису.';
    background: linear-gradient(to right, rgba(240, 246, 255, 0.4), rgba(210, 230, 255, 0.3)) !important;
    border-bottom: 3px solid #003d82 !important;
}


#p-namespaces li.selected a,
                var imgName = extractImageName(content);
#p-views li.selected a {
    color: #003d82 !important;
    font-weight: 700 !important;
}


#p-search {
                if (imgName) {
    background: transparent !important;
                    var fileTitle = imgName.match(/^(Файл|File|Image|Зображення):/i)
    border: none !important;
                        ? imgName
    border-radius: 0 !important;
                        : 'File:' + imgName;
    padding: 2px 6px !important;
    margin-bottom: 0 !important;
}


#simpleSearch {
                    return fetch(
    background: transparent !important;
                        apiBase +
    border: none !important;
                        '?action=query' +
    padding: 0 !important;
                        '&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 };
                    });
                }


#searchInput {
                return Promise.resolve({ title: title, excerpt: excerpt, pageUrl: pageUrl, imgSrc: null });
    background: transparent !important;
            });
    border: none !important;
    font-family: system-ui, -apple-system, sans-serif !important;
    font-size: 14px !important;
    color: #333 !important;
}


/* ── Приховати заголовок на головній ── */
            return Promise.all(promises);
body.page-Головна_сторінка #firstHeading,
        })
body.page-Головна_сторінка .mw-first-heading,
        .then(function(results) {
body.page-Головна_сторінка .firstHeading {
            var list2 = document.getElementById('random-articles-list');
    display: none !important;
            if (!list2) return;
}
            list2.innerHTML = '';


body.page-Головна_сторінка .mw-body-header,
            results.forEach(function(item) {
body.page-Головна_сторінка #content-header {
                var thumbHtml = item.imgSrc
    border-bottom: none !important;
                    ? '<div class="random-article-thumb-wrap"><img class="random-article-thumb" src="' + item.imgSrc + '" alt=""></div>'
    padding-bottom: 0 !important;
                    : '<div class="random-article-thumb-placeholder">📄</div>';
    margin-bottom: 0 !important;
}


/* ════════════════════════════════════
                var card = document.createElement('a');
  VUE CATEGORY CARDS
                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>';


.vcc-app { font-family: inherit; }
                list2.appendChild(card);
 
            });
.vcc-topbar {
        })
    display: flex;
        .catch(function(err) {
    align-items: center;
            var list3 = document.getElementById('random-articles-list');
    gap: 16px;
            if (list3) list3.innerHTML = '<div class="random-articles-loading">Не вдалося завантажити статті.</div>';
    margin-bottom: 16px;
            console.error('[RA] error:', err);
    flex-wrap: wrap;
        });
}
 
.vcc-search {
    flex: 1;
    min-width: 200px;
    max-width: 400px;
    padding: 8px 14px;
    border: 1px solid #d0d7de;
    border-radius: 8px;
    font-size: 14px;
    outline: none;
    transition: border-color .2s, box-shadow .2s;
}
 
.vcc-search:focus {
    border-color: #1a3a6b;
    box-shadow: 0 0 0 3px rgba(26,58,107,.12);
}
 
.vcc-count {
    font-size: 14px;
    color: #555;
    white-space: nowrap;
}
}


.vcc-layout {
mw.hook('wikipage.content').add(function() {
     display: flex;
     var panel = document.getElementById('random-articles-panel');
    gap: 24px;
     if (!panel) return;
     align-items: flex-start;
}


.vcc-main { flex: 1; min-width: 0; }
    loadRandomArticles();


.vcc-grid {
     var btn = document.getElementById('random-articles-refresh');
    display: grid;
     if (btn) {
    gap: 16px;
        btn.addEventListener('click', function() {
}
            loadRandomArticles();
 
        });
.vcc-card {
    display: flex;
    flex-direction: row;
    align-items: center;
    gap: 12px;
    background: #fff;
    border: 1px solid #e8edf3;
    border-radius: 12px;
    padding: 14px;
    text-decoration: none;
    color: inherit;
    transition: box-shadow .2s, transform .2s, border-color .2s;
    cursor: pointer;
    overflow: hidden;
    max-width: 100%;
    box-sizing: border-box;
    min-width: 0;
}
 
.vcc-card:hover {
    box-shadow: 0 4px 18px rgba(0,0,0,.10);
    transform: translateY(-2px);
    border-color: #1a3a6b33;
    text-decoration: none;
    color: inherit;
}
 
.vcc-card-img-wrap {
    flex-shrink: 0;
    width: 56px;
    height: 56px;
    border-radius: 50%;
    overflow: hidden;
    background: #eef2f8;
    display: flex;
    align-items: center;
    justify-content: center;
}
 
.vcc-card-img {
    width: 100%;
    height: 100%;
    object-fit: cover;
}
 
.vcc-card-img-placeholder {
    font-size: 22px;
    font-weight: 700;
    color: #1a3a6b;
    text-transform: uppercase;
}
 
.vcc-card-body { flex: 1; min-width: 0; }
 
.vcc-card-badge {
    display: inline-block;
    font-size: 10px;
    font-weight: 700;
    text-transform: uppercase;
    letter-spacing: .6px;
    color: #b8860b;
    background: #fff8e1;
    border: 1px solid #f0d060;
    border-radius: 4px;
    padding: 2px 6px;
    margin-bottom: 4px;
}
 
.vcc-card-name {
    font-size: 14px;
    font-weight: 600;
    color: #1a3a6b;
    line-height: 1.3;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}
 
.vcc-card-desc {
    font-size: 12px;
    color: #666;
    margin-top: 3px;
    line-height: 1.4;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
    overflow: hidden;
}
 
.vcc-sidebar {
    width: 160px;
    flex-shrink: 0;
    background: #f8f9fb;
     border: 1px solid #e8edf3;
    border-radius: 12px;
    padding: 14px;
}
 
.vcc-sidebar-title {
    font-size: 11px;
    font-weight: 700;
    text-transform: uppercase;
    letter-spacing: .6px;
    color: #888;
    margin-bottom: 10px;
}
 
.vcc-filters { display: flex; flex-direction: column; gap: 6px; }
 
.vcc-filter-btn {
    padding: 7px 12px;
    border: 1px solid #d0d7de;
    border-radius: 8px;
    background: #fff;
    font-size: 13px;
    color: #333;
    cursor: pointer;
    text-align: left;
    transition: background .15s, border-color .15s, color .15s;
}
 
.vcc-filter-btn:hover { background: #eef2f8; border-color: #1a3a6b44; }
 
.vcc-filter-btn.active {
    background: #1a3a6b;
    border-color: #1a3a6b;
    color: #fff;
    font-weight: 600;
}
 
.vcc-loading {
    display: flex;
    align-items: center;
    gap: 12px;
    padding: 40px 0;
    color: #888;
    font-size: 15px;
}
 
.vcc-spinner {
    width: 24px;
    height: 24px;
    border: 3px solid #e0e0e0;
    border-top-color: #1a3a6b;
    border-radius: 50%;
    animation: vcc-spin .8s linear infinite;
}
 
@keyframes vcc-spin { to { transform: rotate(360deg); } }
 
.vcc-empty, .vcc-error {
    text-align: center;
    padding: 48px 0;
    color: #888;
}
 
.vcc-empty-icon { font-size: 36px; margin-bottom: 8px; }
 
.vcc-reset-btn {
    margin-top: 10px;
    padding: 8px 20px;
    border: 1px solid #1a3a6b;
    border-radius: 8px;
    background: #fff;
    color: #1a3a6b;
    cursor: pointer;
    font-size: 13px;
    transition: background .15s;
}
 
.vcc-reset-btn:hover { background: #eef2f8; }
 
.vcc-preview {
    position: absolute;
    z-index: 9999;
    width: 270px;
    background: #fff;
    border: 1px solid #e0e7f0;
    border-radius: 14px;
    box-shadow: 0 8px 32px rgba(0,0,0,.14);
    padding: 16px;
    text-decoration: none;
    color: inherit;
    pointer-events: auto;
}
 
.vcc-preview-top {
    display: flex;
    align-items: center;
    gap: 12px;
    margin-bottom: 10px;
}
 
.vcc-preview-img,
.vcc-preview-img-placeholder {
    width: 52px;
    height: 52px;
    border-radius: 50%;
    object-fit: cover;
    flex-shrink: 0;
    background: #eef2f8;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 20px;
    font-weight: 700;
    color: #1a3a6b;
}
 
.vcc-preview-badge {
    font-size: 10px;
    font-weight: 700;
    text-transform: uppercase;
    letter-spacing: .5px;
    color: #b8860b;
    margin-bottom: 3px;
}
 
.vcc-preview-name {
    font-size: 14px;
    font-weight: 600;
    color: #1a3a6b;
    line-height: 1.3;
}
 
.vcc-preview-divider {
    height: 1px;
    background: #eef2f8;
    margin: 10px 0;
}
 
.vcc-preview-desc {
    font-size: 12px;
    color: #555;
    line-height: 1.5;
    margin-bottom: 8px;
    display: -webkit-box;
    -webkit-line-clamp: 3;
    -webkit-box-orient: vertical;
    overflow: hidden;
}
 
.vcc-preview-row {
    display: flex;
    justify-content: space-between;
    font-size: 12px;
    margin-top: 6px;
    gap: 8px;
}
 
.vcc-preview-lbl { color: #999; white-space: nowrap; }
 
.vcc-preview-val {
    color: #333;
    text-align: right;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}
 
/* ════════════════════════════════════
  МОБІЛЬНА ШАПКА (topbar)
═══════════════════════════════════════ */
 
.mobile-topbar {
    display: none;
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    width: 100%;
    max-width: 100vw;
    height: 52px;
    z-index: 10003;
    align-items: center;
    gap: 8px;
    padding: 0 10px 0 4px;
    box-sizing: border-box;
    background: rgba(255, 255, 255, 0.97);
    backdrop-filter: blur(16px);
    -webkit-backdrop-filter: blur(16px);
    border-bottom: 1px solid rgba(0, 61, 130, 0.1);
    box-shadow: 0 1px 8px rgba(0, 61, 130, 0.07);
}
 
/* ── Кнопка гамбургера ── */
.topbar-menu-btn {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 40px;
    height: 40px;
    background: transparent;
    border: none;
    border-radius: 10px;
    cursor: pointer;
    flex-shrink: 0;
    padding: 0;
    transition: background 0.15s;
    -webkit-tap-highlight-color: transparent;
}
 
.topbar-menu-btn:hover,
.topbar-menu-btn:active {
    background: rgba(0, 61, 130, 0.07);
}
 
.topbar-hamburger {
    display: flex;
    flex-direction: column;
    gap: 5px;
    align-items: center;
     justify-content: center;
}
 
.topbar-hamburger span {
    display: block;
    width: 20px;
    height: 2px;
    background: #003d82;
    border-radius: 2px;
    transition: all 0.25s cubic-bezier(0.165, 0.84, 0.44, 1);
    transform-origin: center;
}
 
/* Анімація в ✕ при відкритому меню */
.topbar-menu-btn.active .topbar-hamburger span:nth-child(1) {
    transform: translateY(7px) rotate(45deg);
}
.topbar-menu-btn.active .topbar-hamburger span:nth-child(2) {
    opacity: 0;
    transform: scaleX(0);
}
.topbar-menu-btn.active .topbar-hamburger span:nth-child(3) {
    transform: translateY(-7px) rotate(-45deg);
}
 
/* Логотип у шапці */
.mobile-topbar-logo {
    display: flex;
    align-items: center;
    gap: 7px;
    text-decoration: none;
    color: #003d82;
    flex-shrink: 0;
    padding: 4px 6px;
    border-radius: 8px;
    transition: background 0.15s;
}
 
.mobile-topbar-logo:hover {
    background: rgba(0, 61, 130, 0.05);
}
 
.mobile-topbar-logo img {
    width: 28px;
    height: 28px;
    object-fit: contain;
    border-radius: 6px;
    max-width: 28px !important;
}
 
.mobile-topbar-logo-text {
    font-family: system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
    font-size: 13px;
    font-weight: 700;
    color: #003d82;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    max-width: 100px;
}
 
/* Пошук у шапці — слот для рідного MediaWiki пошуку */
.mobile-topbar-search {
    flex: 1;
    min-width: 0;
    display: flex;
    align-items: center;
    position: relative;
}
 
/* Рідний блок #p-search всередині топбара */
#mobile-topbar-search-slot {
    flex: 1;
    min-width: 0;
    display: flex;
    align-items: center;
}
 
#mobile-topbar-search-slot #p-search,
#mobile-topbar-search-slot #searchform {
    width: 100% !important;
    margin: 0 !important;
    padding: 0 !important;
    background: transparent !important;
    border: none !important;
    border-radius: 0 !important;
    box-shadow: none !important;
}
 
/* Ховаємо заголовок блоку пошуку */
#mobile-topbar-search-slot h3,
#mobile-topbar-search-slot label[for="searchInput"] {
    display: none !important;
}
 
/* Форма пошуку */
#mobile-topbar-search-slot #simpleSearch,
#mobile-topbar-search-slot form {
    display: flex !important;
    align-items: center !important;
    width: 100% !important;
    background: rgba(0, 61, 130, 0.05) !important;
    border: 1px solid rgba(0, 61, 130, 0.12) !important;
    border-radius: 20px !important;
    padding: 0 8px 0 12px !important;
    height: 34px !important;
    box-sizing: border-box !important;
    transition: border-color 0.15s, box-shadow 0.15s, background 0.15s !important;
    margin: 0 !important;
}
 
#mobile-topbar-search-slot #simpleSearch:focus-within,
#mobile-topbar-search-slot form:focus-within {
    border-color: rgba(0, 61, 130, 0.35) !important;
    box-shadow: 0 0 0 3px rgba(0, 61, 130, 0.07) !important;
    background: #fff !important;
}
 
/* Поле вводу */
#mobile-topbar-search-slot #searchInput,
#mobile-topbar-search-slot input[type="search"],
#mobile-topbar-search-slot input[name="search"] {
    flex: 1 !important;
    border: none !important;
    background: transparent !important;
    outline: none !important;
    box-shadow: none !important;
    font-size: 13.5px !important;
    color: #333 !important;
    min-width: 0 !important;
    width: 100% !important;
    max-width: none !important;
    padding: 0 !important;
    height: auto !important;
    line-height: normal !important;
}
 
#mobile-topbar-search-slot input::placeholder {
    color: #aaa !important;
}
 
/* Кнопка пошуку (лупа) */
#mobile-topbar-search-slot #searchButton,
#mobile-topbar-search-slot button[type="submit"] {
    background: transparent !important;
    border: none !important;
    padding: 2px !important;
    margin: 0 !important;
    cursor: pointer !important;
    color: #999 !important;
    display: flex !important;
    align-items: center !important;
    justify-content: center !important;
    flex-shrink: 0 !important;
    width: 22px !important;
    height: 22px !important;
    border-radius: 50% !important;
    transition: color 0.15s, background 0.15s !important;
}
 
#mobile-topbar-search-slot #searchButton:hover,
#mobile-topbar-search-slot button[type="submit"]:hover {
    color: #003d82 !important;
    background: rgba(0, 61, 130, 0.08) !important;
}
 
/* Автокомпліт (suggestions) — позиціонуємо під формою */
#mobile-topbar-search-slot .suggestions {
    position: fixed !important;
    top: 52px !important;
    width: auto !important;
    min-width: 200px !important;
    z-index: 10020 !important;
    border-radius: 0 0 12px 12px !important;
    box-shadow: 0 8px 24px rgba(0, 61, 130, 0.12) !important;
}
 
/* ── Юзер-аватар ── */
.topbar-user-wrap {
    position: static; /* дропдаун буде fixed, тому static тут достатньо */
    flex-shrink: 0;
}
 
.topbar-user-avatar {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 34px;
    height: 34px;
    border-radius: 50%;
    background: linear-gradient(135deg, #003d82, #0066cc);
    color: #fff;
    font-family: system-ui, -apple-system, sans-serif;
    font-size: 14px;
    font-weight: 700;
    cursor: pointer;
    user-select: none;
    -webkit-tap-highlight-color: transparent;
    transition: box-shadow 0.15s, transform 0.15s;
    box-shadow: 0 2px 8px rgba(0, 61, 130, 0.25);
}
 
.topbar-user-avatar:hover {
    box-shadow: 0 4px 14px rgba(0, 61, 130, 0.35);
    transform: scale(1.05);
}
 
.topbar-login-btn {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 34px;
    height: 34px;
    border-radius: 50%;
    color: #555;
    text-decoration: none;
    transition: background 0.15s, color 0.15s;
}
 
.topbar-login-btn:hover {
    background: rgba(0, 61, 130, 0.07);
    color: #003d82;
}
 
/* ── Дропдаун — fixed щоб не виходив за межі ── */
.topbar-user-dropdown {
    position: fixed;
    top: 52px; /* одразу під топбаром */
    right: 8px; /* завжди притягнутий до правого краю */
    left: auto;
    width: 210px;
    background: #fff;
    border: 1px solid rgba(0, 61, 130, 0.1);
    border-radius: 14px;
    box-shadow: 0 8px 32px rgba(0, 61, 130, 0.14), 0 2px 8px rgba(0,0,0,0.06);
    overflow: hidden;
    opacity: 0;
    transform: translateY(-6px) scale(0.97);
    pointer-events: none;
    transition: opacity 0.18s ease, transform 0.18s ease;
    z-index: 10015;
}
 
.topbar-user-dropdown.open {
    opacity: 1;
    transform: translateY(0) scale(1);
    pointer-events: auto;
}
 
.topbar-dropdown-header {
    display: flex;
    align-items: center;
    gap: 10px;
    padding: 14px 14px 12px;
    background: linear-gradient(135deg, rgba(0,61,130,0.04), rgba(0,102,204,0.06));
}
 
.topbar-dropdown-avatar {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 32px;
    height: 32px;
    border-radius: 50%;
    background: linear-gradient(135deg, #003d82, #0066cc);
    color: #fff;
    font-size: 13px;
    font-weight: 700;
    flex-shrink: 0;
}
 
.topbar-dropdown-name {
    font-family: system-ui, -apple-system, sans-serif;
    font-size: 13px;
    font-weight: 600;
    color: #003d82;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}
 
.topbar-dropdown-divider {
    height: 1px;
    background: rgba(0, 61, 130, 0.07);
    margin: 0;
}
 
.topbar-dropdown-item {
    display: flex;
    align-items: center;
    gap: 9px;
    padding: 11px 14px;
    font-family: system-ui, -apple-system, sans-serif;
    font-size: 13.5px;
    color: #333;
    text-decoration: none;
    transition: background 0.13s;
    cursor: pointer;
}
 
.topbar-dropdown-item svg {
    color: #666;
    flex-shrink: 0;
}
 
.topbar-dropdown-item:hover {
    background: rgba(0, 61, 130, 0.05);
    color: #003d82;
    text-decoration: none;
}
 
.topbar-dropdown-item:hover svg {
    color: #003d82;
}
 
.topbar-dropdown-logout {
    color: #c0392b;
}
 
.topbar-dropdown-logout svg {
    color: #c0392b;
}
 
.topbar-dropdown-logout:hover {
    background: rgba(192, 57, 43, 0.06);
    color: #c0392b;
}
 
/* ════════════════════════════════════
  МОБІЛЬНЕ МЕНЮ — ОВЕРЛЕЙ
═══════════════════════════════════════ */
 
.mobile-menu-toggle {
    display: none !important;
}
 
.mobile-menu-overlay {
    display: none;
    position: fixed;
    inset: 0;
    background: rgba(0, 0, 0, 0.4);
    z-index: 10000;
    backdrop-filter: blur(2px);
}
 
.mobile-menu-overlay.open {
    display: block;
}
 
body.mobile-nav-open #mw-panel {
    transform: translateX(0) !important;
    box-shadow: 4px 0 32px rgba(0, 61, 130, 0.18) !important;
}
 
/* Прибираємо нижню панель — більше не використовується */
.mobile-bottom-nav {
    display: none !important;
}
 
/* ════════════════════════════════════
  АДАПТИВНІСТЬ — BREAKPOINTS
═══════════════════════════════════════ */
 
/* ── 1280px: трохи звужуємо праву колонку ── */
@media (max-width: 1280px) {
    .right-column {
        width: 300px;
        min-width: 300px;
     }
     }
    .section-categories {
});
        margin-right: calc(300px + 24px);
    }
    .card-image img {
        width: 190px;
        height: 190px;
    }
}


/* ── 1100px: планшет landscape — мобільна шапка ── */
/* ══════════════════════════════════════════════
@media (max-width: 1100px) {
  Vue-додаток для категорій MediaWiki
══════════════════════════════════════════════ */


    /* Показуємо мобільну шапку */
mw.hook('wikipage.content').add(function () {
     .mobile-topbar {
     var mountEl = document.getElementById('vue-category-cards');
        display: flex !important;
    if (!mountEl) return;
    }


     /* Відступ зверху для контенту (під мобільну шапку 52px) */
     var categoryName  = mountEl.getAttribute('data-category')    || '';
     #mw-body,
     var filterField  = mountEl.getAttribute('data-filter-field') || 'auto';
     .mw-body,
     var pageLimit     = parseInt(mountEl.getAttribute('data-limit') || '50', 10);
     #content,
     var columns      = mountEl.getAttribute('data-columns')      || '3';
     #bodyContent,
     .mw-page-container {
        padding-top: 52px !important;
        box-sizing: border-box !important;
    }


     /* Без відступу знизу — нижнього таббара більше немає */
     if (!categoryName) {
    body {
         mountEl.innerHTML = '<p style="color:red">Вкажіть атрибут data-category</p>';
         padding-bottom: 0 !important;
        return;
     }
     }


     /* Ховаємо оригінальну шапку MediaWiki повністю */
     // Визначаємо чи touch-пристрій (для відключення превью)
    #mw-head,
     var isTouch = ('ontouchstart' in window) || (navigator.maxTouchPoints > 0);
    #mw-head-base,
    #p-personal,
     #mw-page-base {
        display: none !important;
    }


     /* Бокова навігація — ховається за екран зліва */
     mw.loader.getScript('https://unpkg.com/vue@3/dist/vue.global.prod.js').then(function () {
    #mw-panel {
        position: fixed !important;
        top: 52px !important;
        left: 0 !important;
        height: calc(100vh - 52px) !important;
        width: 280px !important;
        overflow-y: auto !important;
        z-index: 10002 !important;
        padding: 16px 12px 24px !important;
        margin: 0 !important;
        transform: translateX(-100%) !important;
        transition: transform 0.3s cubic-bezier(0.165, 0.84, 0.44, 1) !important;
        background: rgba(248, 251, 255, 0.98) !important;
        backdrop-filter: blur(20px) !important;
        -webkit-backdrop-filter: blur(20px) !important;
        border-right: 1px solid rgba(0, 61, 130, 0.12) !important;
    }


    /* Контент займає весь екран */
        var apiBase = mw.config.get('wgScriptPath') + '/api.php';
    #mw-content-column,
    .mw-content-column,
    #content,
    .mw-body {
        margin-left: 0 !important;
        width: 100% !important;
        max-width: 100% !important;
    }


    /* Welcome — стек */
        function parseField(wikitext, field) {
    .welcome-wrapper {
            if (!wikitext || !field) return '';
        flex-direction: column;
            var re = new RegExp('\\|\\s*' + field + '\\s*=\\s*([^\\|\\n\\}]+)', 'i');
        text-align: center;
            var m = wikitext.match(re);
        gap: 24px;
            return m ? m[1].trim() : '';
        padding: 32px 5vw 28px;
        }
    }


    .welcome-text {
        function parseInfobox(wikitext) {
        transform: none;
            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;
        }


    .welcome-title {
        function resolveFilterValue(fields, explicit) {
        font-size: 2rem;
            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()] || '';
        }


    .welcome-subtitle {
        function toFilterLabel(val) {
        font-size: 1.2rem;
            if (!val) return 'Інше';
    }
            if (val.length <= 12) return val;
            return val.split(/[\s,]/)[0];
        }


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


    /* Заголовок категорій — без правого відступу */
            computed: {
    .section-categories {
                filteredItems() {
        margin-right: 0;
                    var vm = this;
        font-size: 1.8rem;
                    var q = vm.searchQuery.trim().toLowerCase();
    }
                    return vm.items.filter(function (item) {
                        var matchFilter = vm.activeFilter === 'Всі' || item.filterLabel === vm.activeFilter;
                        var matchSearch = !q || item.title.toLowerCase().includes(q) ||
                            (item.description && item.description.toLowerCase().includes(q));
                        return matchFilter && matchSearch;
                    }).slice().sort(function (a, b) {
                        return a.title.localeCompare(b.title, 'uk');
                    });
                },


    /* Layout — стек */
                gridStyle() {
    .main-content-layout {
                    // На маленьких екранах примусово 1 колонка
        flex-direction: column;
                    if (window.innerWidth <= 480) return 'grid-template-columns: 1fr;';
        padding: 0 4vw;
                    return 'grid-template-columns: repeat(' + this.gridColumns + ', 1fr);';
        gap: 20px;
                }
    }
            },


    .category-column {
            mounted() {
        width: 100%;
                this.loadItems();
    }
            },


    /* Права колонка — горизонтально */
            methods: {
    .right-column {
                showPreview(item, event) {
        width: 100%;
                    // Відключаємо превью на touch-пристроях
        min-width: unset;
                    if (this.isTouch) return;
        flex-direction: row;
                    var vm = this;
        flex-wrap: wrap;
                    clearTimeout(vm.previewTimer);
        gap: 16px;
                    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);
                },


    .right-column > * {
                async loadItems() {
        flex: 1 1 280px;
                    this.loading = true;
        min-width: 280px;
                    this.error  = null;
    }
                    try {
                        var catResp = await fetch(
                            apiBase + '?action=query&list=categorymembers' +
                            '&cmtitle=' + encodeURIComponent('Категорія:' + categoryName) +
                            '&cmlimit=' + pageLimit + '&cmnamespace=0&format=json'
                        );
                        var catData = await catResp.json();
                        var members = (catData.query || {}).categorymembers || [];


    /* Сітка категорій — 3 колонки */
                        if (!members.length) { this.loading = false; return; }
    .category-grid-container {
        grid-template-columns: repeat(3, 1fr);
    }


    .card-image img {
                        var titles = members.map(function (m) { return m.title; }).join('|');
        width: 160px;
        height: 160px;
    }
}


/* ── 820px: планшет portrait — 2 колонки ── */
                        var pageResp = await fetch(
@media (max-width: 820px) {
                            apiBase + '?action=query&titles=' + encodeURIComponent(titles) +
    .category-grid-container {
                            '&prop=revisions&rvprop=content&format=json'
        grid-template-columns: repeat(2, 1fr);
                        );
    }
                        var pageData = await pageResp.json();
                        var pages    = Object.values((pageData.query || {}).pages || {});


    .card-image img {
                        var filterSet = new Set();
        width: 140px;
        height: 140px;
    }


    .welcome-title {
                        var promises = pages.map(async function (page) {
        font-size: 1.75rem;
                            var content = (page.revisions && page.revisions[0])
    }
                                ? (page.revisions[0]['*'] || '') : '';


    /* Ресурси */
                            var fields      = parseInfobox(content);
    .resources-and-contacts {
                            var filterVal  = resolveFilterValue(fields, filterField === 'auto' ? 'auto' : filterField);
        flex-direction: column;
                            var filterLabel = toFilterLabel(filterVal);
        gap: 16px;
                            if (filterLabel) filterSet.add(filterLabel);
        margin: 30px 4vw 40px;
    }


    .resource-block,
                            var description = extractDescription(content);
     .contacts-block {
                            var imgName     = extractImageName(content);
        min-width: unset;
                            var imgSrc      = null;
        width: 100%;
    }


    /* VCC фільтри — горизонтально зверху */
                            if (imgName) {
    .vcc-layout {
                                try {
        flex-direction: column-reverse;
                                    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 */ }
                            }


    .vcc-sidebar {
                            var pageUrl = mw.config.get('wgArticlePath').replace(
        width: 100%;
                                '$1', encodeURIComponent(page.title.replace(/ /g, '_'))
        padding: 12px;
                            );
    }


    .vcc-filters {
                            var extra = [];
        flex-direction: row;
                            var extraKeys = ['посада', 'position', 'occupation', 'спеціальність',
        flex-wrap: wrap;
                                            'рік', 'рубрика', 'тип', 'автор', 'faculty'];
        gap: 8px;
                            extraKeys.forEach(function (k) {
    }
                                if (fields[k] && fields[k] !== filterVal) {
                                    extra.push({ label: k, value: fields[k] });
                                }
                            });


    .vcc-filter-btn {
                            return {
        flex: 0 0 auto;
                                title:      page.title,
        font-size: 12px;
                                filterLabel: filterLabel || 'Інше',
        padding: 5px 10px;
                                description: description,
    }
                                imgSrc:     imgSrc,
                                pageUrl:     pageUrl,
                                extra:       extra.slice(0, 3),
                            };
                        });


    .vcc-sidebar-title {
                        this.items = await Promise.all(promises);
        margin-bottom: 8px;
    }
}


/* ── 600px: великий мобільний ── */
                        var sortedFilters = Array.from(filterSet).sort(function (a, b) {
@media (max-width: 600px) {
                            return a.localeCompare(b, 'uk');
    .category-grid-container {
                        });
        grid-template-columns: repeat(2, 1fr);
                        this.filters = ['Всі'].concat(sortedFilters);
        gap: 12px;
    }


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


    .card-title {
            template: `
        font-size: 13px;
<div class="vcc-app">
        padding: 6px 8px 10px;
    }


     .welcome-wrapper {
  <div class="vcc-topbar">
        padding: 24px 4vw 20px;
     <input
        gap: 18px;
      class="vcc-search"
    }
      type="text"
      v-model="searchQuery"
      placeholder="Пошук..."
    />
    <span class="vcc-count" v-if="!loading">
      Знайдено: <strong>{{ filteredItems.length }}</strong> з {{ items.length }}
    </span>
  </div>


    .welcome-title {
  <div class="vcc-layout">
        font-size: 1.5rem;
    }


     .welcome-subtitle {
     <div class="vcc-main">
        font-size: 1rem;
    }


    .section-categories {
      <div class="vcc-loading" v-if="loading">
         font-size: 1.5rem;
         <div class="vcc-spinner"></div>
         margin: 20px 0 20px;
         <span>Завантаження...</span>
    }
      </div>
 
    .main-content-layout {
        padding: 0 3vw;
    }
 
    /* Випадкові статті — менший thumb */
    .random-article-thumb-wrap,
    .random-article-thumb-placeholder {
        width: 64px;
        height: 64px;
        min-width: 64px;
        min-height: 64px;
    }


    .random-article-title {
      <div class="vcc-error" v-else-if="error">{{ error }}</div>
        font-size: 13px;
    }


    .random-article-excerpt {
      <div class="vcc-empty" v-else-if="!filteredItems.length">
         font-size: 12px;
        <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>
    .right-column {
         <a
         flex-direction: column;
          v-for="item in filteredItems"
    }
          :key="item.title"
 
          :href="item.pageUrl"
    .right-column > * {
          class="vcc-card"
        min-width: unset;
          @mouseenter="showPreview(item, $event)"
        width: 100%;
          @mouseleave="hidePreview"
    }
        >
}
          <div class="vcc-card-img-wrap">
 
            <img v-if="item.imgSrc" :src="item.imgSrc" :alt="item.title" class="vcc-card-img" />
/* ── 480px: мобільний ── */
            <div v-else class="vcc-card-img-placeholder">{{ item.title.charAt(0) }}</div>
@media (max-width: 480px) {
          </div>
    .category-grid-container {
          <div class="vcc-card-body">
        grid-template-columns: 1fr 1fr;
            <div v-if="item.filterLabel && item.filterLabel !== 'Інше'"
        gap: 10px;
                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>
    .card-image {
          </div>
         padding: 14px 0 8px;
         </a>
     }
      </div>
     </div>


     .card-image img {
     <div class="vcc-sidebar" v-if="filters.length > 2">
         width: 90px;
      <div class="vcc-sidebar-title">Фільтр</div>
         height: 90px;
      <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>


    .welcome-title {
  </div>
        font-size: 1.35rem;
    }


     .section-categories {
  <teleport to="body" v-if="!isTouch">
         font-size: 1.3rem;
     <a
     }
      v-if="preview"
      :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>


    .vcc-grid {
</div>
         grid-template-columns: 1fr !important;
            `
    }
         });


    /* Ресурси */
        app.mount('#vue-category-cards');
    .resource-block,
     });
     .contacts-block {
});
        padding: 18px 16px 20px;
    }


    .resource-block h2,
/* ══════════════════════════════════════════════
    .contacts-block h2 {
  ГОЛОВНА СТОРІНКА
        font-size: 1.15rem !important;
══════════════════════════════════════════════ */
    }


     .resource-block li,
/* ── Анімація чисел статистики ── */
     .contacts-block li {
function animateNumber(element, target) {
         font-size: 13px;
     element.classList.add('animating');
         padding: 7px 10px 7px 24px;
    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);
}
}


/* ── 360px: дуже маленький мобільний ── */
mw.hook('wikipage.content').add(function() {
@media (max-width: 360px) {
    if (mw.config.get('wgPageName') !== 'Головна_сторінка') return;
     .category-grid-container {
   
         grid-template-columns: 1fr;
     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();
});


     .card-image img {
/* ── Сортування карточок за прізвищем ── */
         width: 120px;
mw.hook('wikipage.content').add(function() {
         height: 120px;
     document.querySelectorAll('div[style*="grid-template-columns"]').forEach(function(grid) {
    }
         var cards = Array.from(grid.children);
         if (cards.length < 2) return;


    .welcome-title {
        cards.sort(function(a, b) {
        font-size: 1.2rem;
            var aLink = a.querySelector('div[style*="flex-grow"] a');
    }
            var bLink = b.querySelector('div[style*="flex-grow"] a');
            if (!aLink || !bLink) return 0;


    .section-categories {
            var aSurname = aLink.textContent.trim().split(' ')[0];
        font-size: 1.1rem;
            var bSurname = bLink.textContent.trim().split(' ')[0];
    }
}


/* ════════════════════════════════════
            return aSurname.localeCompare(bSurname, 'uk');
  TOUCH DEVICES: прибираємо hover-анімації
         });
═══════════════════════════════════════ */
@media (hover: none) and (pointer: coarse) {
    .category-card:hover {
        transform: none;
         box-shadow: 0 6px 24px rgba(0,0,0,0.08);
    }


    .category-card:hover .card-image img {
        cards.forEach(function(card) {
         animation: none;
            grid.appendChild(card);
        transform: none;
         });
    }
    });
});


     .category-card:hover::before {
/* ── Прогрес скролла ── */
         opacity: 0;
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();
});


     .random-article-card:hover {
/* ── Particles.js canvas фон ── */
        transform: none;
mw.hook('wikipage.content').add(function() {
     }
     if (mw.config.get('wgPageName') !== 'Головна_сторінка') return;
   
    var welcomeWrapper = document.querySelector('.welcome-wrapper');
     if (!welcomeWrapper) return;


     .resource-block:hover,
     // Не запускаємо частинки на мобільних (економія батареї)
    .contacts-block:hover {
     if (window.innerWidth < 768) return;
        transform: none;
    }
 
    body #mw-panel .portal:hover {
        transform: none !important;
    }
 
    .vcc-card:hover {
        transform: none;
        box-shadow: 0 2px 8px rgba(0,0,0,0.06);
    }
 
    .category-card:active {
        transform: scale(0.98);
        box-shadow: 0 4px 16px rgba(0, 61, 130, 0.15);
    }
 
    .vcc-card:active {
        transform: scale(0.98);
    }
}
 
/* ════════════════════════════════════
  PRINT
═══════════════════════════════════════ */
@media print {
    #mw-panel,
    .scroll-progress,
    .mobile-topbar,
    .mobile-menu-overlay,
    .random-articles-panel,
    .stats-panel {
        display: none !important;
    }
 
    .main-content-layout {
        flex-direction: column;
        padding: 0;
    }
 
    .category-grid-container {
        grid-template-columns: repeat(3, 1fr);
        gap: 8px;
    }
 
    .category-card {
        box-shadow: none;
        border: 1px solid #ccc;
    }
}
 
/* ════════════════════════════════════
  ІНФОБОКС ТА ЗОБРАЖЕННЯ В СТАТТЯХ
═══════════════════════════════════════ */
 
/* Картинки в статтях — завжди масштабуються */
.mw-parser-output img,
.mw-parser-output .thumbimage img,
.mw-parser-output .infobox img {
    max-width: 100% !important;
    height: auto !important;
}
 
/* thumb/frame обгортки */
.mw-parser-output .thumb,
.mw-parser-output .thumbinner {
    max-width: 100% !important;
    box-sizing: border-box !important;
}
 
/* Таблиці — не виходять за межі */
.mw-parser-output table,
.mw-parser-output .infobox,
.mw-parser-output .wikitable {
    max-width: 100% !important;
    box-sizing: border-box !important;
    word-break: break-word !important;
}
 
/* ── Мобільні ≤1100px ── */
@media (max-width: 1100px) {
 
    /* Інфобокс — знімаємо float, на всю ширину */
    .mw-parser-output .infobox,
    .mw-parser-output table.infobox {
        float: none !important;
        margin: 0 0 20px 0 !important;
        width: 100% !important;
        max-width: 100% !important;
        display: table !important;
    }
 
    /* Таблиці — горизонтальний скрол */
    .mw-parser-output .wikitable {
        display: block !important;
        overflow-x: auto !important;
        -webkit-overflow-scrolling: touch !important;
    }
 
    /* Всі float-картинки — знімаємо float */
    .mw-parser-output .thumb,
    .mw-parser-output .thumb.tright,
    .mw-parser-output .thumb.tleft,
    .mw-parser-output .thumbinner,
    .mw-parser-output .floatright,
    .mw-parser-output .floatleft,
    .mw-parser-output [style*="float: right"],
    .mw-parser-output [style*="float:right"],
    .mw-parser-output [style*="float: left"],
    .mw-parser-output [style*="float:left"] {
        float: none !important;
        display: block !important;
        margin: 0 auto 16px !important;
        max-width: 100% !important;
        width: auto !important;
        clear: both !important;
    }
 
    .mw-parser-output .thumb img,
    .mw-parser-output .thumbinner img {
        max-width: 100% !important;
        width: 100% !important;
        height: auto !important;
        display: block !important;
        margin: 0 auto !important;
    }
 
    /* Thumb-блоки — перебиваємо inline width від MediaWiki (style="width:Npx") */
    .mw-parser-output .thumb,
    .mw-parser-output .thumb.tright,
    .mw-parser-output .thumb.tleft,
    .mw-parser-output .thumbinner,
    .mw-parser-output .thumb[style],
    .mw-parser-output .thumbinner[style] {
        width: clamp(120px, 48vw, 280px) !important;
        max-width: clamp(120px, 48vw, 280px) !important;
        box-sizing: border-box !important;
    }
 
    .mw-parser-output .thumbcaption {
        text-align: center !important;
    }
 
    /* Інфобокс: фото масштабується пропорційно ширині екрану.
      На 480px → ~44vw, на 600px → ~200px.
      Колонка з фото не ширша за необхідне. */
    .mw-parser-output .infobox td:has(img),
    .mw-parser-output table.infobox td:has(img) {
        width: clamp(100px, 44vw, 220px) !important;
        max-width: clamp(100px, 44vw, 220px) !important;
        padding: 6px !important;
    }
 
    .mw-parser-output .infobox td:has(img) img,
    .mw-parser-output table.infobox td:has(img) img {
        width: 100% !important;
        max-width: 100% !important;
        height: auto !important;
        display: block !important;
    }
}
 
/* ── Маленькі екрани ≤430px: інфобокс вертикально ── */
@media (max-width: 430px) {
 
    /* Вся таблиця стає вертикальною */
    .mw-parser-output .infobox,
     .mw-parser-output table.infobox {
        display: block !important;
    }
 
    .mw-parser-output .infobox tbody,
    .mw-parser-output table.infobox tbody {
        display: block !important;
    }
 
    /* Кожен рядок — блок */
    .mw-parser-output .infobox tr,
    .mw-parser-output table.infobox tr {
        display: block !important;
        border-bottom: 1px solid rgba(0,0,0,0.07) !important;
        overflow: hidden !important;
    }


     /* Комірки — блоки */
     // Не запускаємо при prefers-reduced-motion
     .mw-parser-output .infobox td,
     if (window.matchMedia('(prefers-reduced-motion: reduce)').matches) return;
     .mw-parser-output .infobox th,
   
     .mw-parser-output table.infobox td,
    var canvas = document.createElement('canvas');
     .mw-parser-output table.infobox th {
    canvas.className = 'particles-canvas';
        display: block !important;
     canvas.style.cssText = 'position:absolute;top:0;left:0;width:100%;height:100%;pointer-events:none;z-index:0;';
        width: 100% !important;
   
         max-width: 100% !important;
    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%)';
         box-sizing: border-box !important;
     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%)';
         text-align: center !important;
     canvas.style.webkitMaskComposite = 'source-in';
         padding: 6px 10px !important;
    canvas.style.maskComposite = 'intersect';
         border: none !important;
    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() {
    .mw-parser-output .infobox caption,
        ctx.beginPath();
     .mw-parser-output table.infobox caption {
        ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2);
         font-size: 14px !important;
        ctx.fillStyle = 'rgba(255, 215, 0, 0.6)';
         font-weight: 700 !important;
        ctx.fill();
         padding: 10px 12px 6px !important;
    };
         display: block !important;
   
     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());
     }
     }
 
   
     /* Фото — на всю ширину, не більше 260px */
     function animate() {
    .mw-parser-output .infobox img,
        ctx.clearRect(0, 0, canvas.width, canvas.height);
    .mw-parser-output table.infobox img {
       
        width: 100% !important;
        for (var i = 0; i < particles.length; i++) {
        max-width: 260px !important;
            particles[i].update();
        height: auto !important;
            for (var j = i + 1; j < particles.length; j++) {
         border-radius: 8px !important;
                var dx = particles[i].x - particles[j].x;
         display: block !important;
                var dy = particles[i].y - particles[j].y;
         margin: 4px auto !important;
                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);
     }
     }
 
   
     /* Рядки з th+td (назва + значення) — горизонтально */
     animate();
     .mw-parser-output .infobox tr:has(th + td),
   
    .mw-parser-output table.infobox tr:has(th + td) {
    var resizeTimer;
         display: flex !important;
     window.addEventListener('resize', function() {
         align-items: flex-start !important;
         clearTimeout(resizeTimer);
    }
         resizeTimer = setTimeout(function() {
 
            canvas.width = welcomeWrapper.offsetWidth;
    .mw-parser-output .infobox tr:has(th + td) th,
            canvas.height = welcomeWrapper.offsetHeight;
    .mw-parser-output table.infobox tr:has(th + td) th {
            // На мобільних зупиняємо анімацію після resize
        width: 38% !important;
            if (window.innerWidth < 768) {
        text-align: left !important;
                cancelAnimationFrame(animId);
        font-size: 12px !important;
                canvas.remove();
        font-weight: 600 !important;
            }
        color: #555 !important;
         }, 200);
        padding: 7px 6px 7px 10px !important;
     });
    }
});
 
    .mw-parser-output .infobox tr:has(th + td) td,
    .mw-parser-output table.infobox tr:has(th + td) td {
        width: 62% !important;
        text-align: left !important;
         font-size: 13px !important;
        padding: 7px 10px 7px 6px !important;
     }
}

Версія за 10:59, 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';

    // Визначаємо URL логотипа та головної сторінки
    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);

    // Переміщуємо рідний пошуковий блок MediaWiki у топбар
    var nativeSearch = document.getElementById('p-search');
    if (!nativeSearch) nativeSearch = document.getElementById('searchform');
    if (!nativeSearch) nativeSearch = document.querySelector('form[action*="search"]');
    var searchSlot = document.getElementById('mobile-topbar-search-slot');
    if (nativeSearch && searchSlot) {
        searchSlot.appendChild(nativeSearch);
    }

    // Дропдаун юзера — position:fixed, завжди правий край
    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-КАРТИНОК
   CSS не може перебити inline style="width:Npx" від MediaWiki,
   тому знімаємо його через JS на мобільних
══════════════════════════════════════════════ */
mw.hook('wikipage.content').add(function() {
    function fixThumbWidths() {
        if (window.innerWidth > 1100) return;

        var vw = window.innerWidth;
        // clamp(120, 48vw, 280) — та сама формула що в CSS
        var targetWidth = Math.min(280, Math.max(120, Math.round(vw * 0.48)));

        // .thumbinner — основний контейнер з inline style="width:Npx"
        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');
        });

        // img всередині thumb — на всю ширину контейнера
        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 });
});




/* ══════════════════════════════════════════════
   ГЛОБАЛЬНІ ПАРСЕРИ
══════════════════════════════════════════════ */
    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') || '50', 10);
    var columns       = mountEl.getAttribute('data-columns')       || '3';

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

    // Визначаємо чи touch-пристрій (для відключення превью)
    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 parseField(wikitext, field) {
            if (!wikitext || !field) return '';
            var re = new RegExp('\\|\\s*' + field + '\\s*=\\s*([^\\|\\n\\}]+)', 'i');
            var m = wikitext.match(re);
            return m ? m[1].trim() : '';
        }

        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 toFilterLabel(val) {
            if (!val) return 'Інше';
            if (val.length <= 12) return val;
            return val.split(/[\s,]/)[0];
        }

        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();
                    return vm.items.filter(function (item) {
                        var matchFilter = vm.activeFilter === 'Всі' || item.filterLabel === vm.activeFilter;
                        var matchSearch = !q || item.title.toLowerCase().includes(q) ||
                            (item.description && item.description.toLowerCase().includes(q));
                        return matchFilter && matchSearch;
                    }).slice().sort(function (a, b) {
                        return a.title.localeCompare(b.title, 'uk');
                    });
                },

                gridStyle() {
                    // На маленьких екранах примусово 1 колонка
                    if (window.innerWidth <= 480) return 'grid-template-columns: 1fr;';
                    return 'grid-template-columns: repeat(' + this.gridColumns + ', 1fr);';
                }
            },

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

            methods: {
                showPreview(item, event) {
                    // Відключаємо превью на touch-пристроях
                    if (this.isTouch) 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 {
                        var catResp = await fetch(
                            apiBase + '?action=query&list=categorymembers' +
                            '&cmtitle=' + encodeURIComponent('Категорія:' + categoryName) +
                            '&cmlimit=' + pageLimit + '&cmnamespace=0&format=json'
                        );
                        var catData = await catResp.json();
                        var members = (catData.query || {}).categorymembers || [];

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

                        var titles = members.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 pages    = Object.values((pageData.query || {}).pages || {});

                        var filterSet = new Set();

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

                            var fields      = parseInfobox(content);
                            var filterVal   = resolveFilterValue(fields, filterField === 'auto' ? 'auto' : filterField);
                            var filterLabel = toFilterLabel(filterVal);
                            if (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 = [];
                            var extraKeys = ['посада', 'position', 'occupation', 'спеціальність',
                                             'рік', 'рубрика', 'тип', 'автор', 'faculty'];
                            extraKeys.forEach(function (k) {
                                if (fields[k] && fields[k] !== filterVal) {
                                    extra.push({ label: k, value: fields[k] });
                                }
                            });

                            return {
                                title:       page.title,
                                filterLabel: filterLabel || 'Інше',
                                description: description,
                                imgSrc:      imgSrc,
                                pageUrl:     pageUrl,
                                extra:       extra.slice(0, 3),
                            };
                        });

                        this.items = await Promise.all(promises);

                        var sortedFilters = Array.from(filterSet).sort(function (a, b) {
                            return a.localeCompare(b, 'uk');
                        });
                        this.filters = ['Всі'].concat(sortedFilters);

                    } 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"
      :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();
});

/* ── Particles.js canvas фон ── */
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;

    // Не запускаємо при prefers-reduced-motion
    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;
            // На мобільних зупиняємо анімацію після resize
            if (window.innerWidth < 768) {
                cancelAnimationFrame(animId);
                canvas.remove();
            }
        }, 200);
    });
});