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

Матеріал з Київський національний лінгвістичний університет
Перейти до навігації Перейти до пошуку
Немає опису редагування
Немає опису редагування
Рядок 3: Рядок 3:
     var viewport = document.querySelector('meta[name="viewport"]');
     var viewport = document.querySelector('meta[name="viewport"]');
     if (viewport) {
     if (viewport) {
         viewport.setAttribute('content', 'width=device-width, initial-scale=1.0, viewport-fit=cover');
         viewport.setAttribute('content', 'width=device-width, initial-scale=1.0, maximum-scale=5.0, viewport-fit=cover');
     } else {
     } else {
         var meta = document.createElement('meta');
         var meta = document.createElement('meta');
         meta.name = 'viewport';
         meta.name = 'viewport';
         meta.content = 'width=device-width, initial-scale=1.0, viewport-fit=cover';
         meta.content = 'width=device-width, initial-scale=1.0, maximum-scale=5.0, viewport-fit=cover';
         document.head.appendChild(meta);
         document.head.appendChild(meta);
     }
     }
Рядок 35: Рядок 35:


/* ══════════════════════════════════════════════
/* ══════════════════════════════════════════════
   МОБІЛЬНЕ МЕНЮ
   МОБІЛЬНА ШАПКА + НИЖНІЙ ТАББАР
══════════════════════════════════════════════ */
══════════════════════════════════════════════ */


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


     // Створюємо оверлей
     /* ── Оверлей ── */
     var overlay = document.createElement('div');
     var overlay = document.createElement('div');
     overlay.className = 'mobile-menu-overlay';
     overlay.className = 'mobile-menu-overlay';
     document.body.appendChild(overlay);
     document.body.appendChild(overlay);


     // Створюємо кнопку-гамбургер
     /* ── Мобільна шапка ── */
     var btn = document.createElement('button');
     var topbar = document.createElement('div');
     btn.className = 'mobile-menu-toggle';
     topbar.className = 'mobile-topbar';
    btn.setAttribute('aria-label', 'Відкрити меню');
    btn.innerHTML = '☰';
    document.body.appendChild(btn);


    // Визначаємо 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 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;">' + (siteName.charAt(0) || '🏛') + '</span>';
    topbar.innerHTML =
        '<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">' +
            '<span class="mobile-topbar-search-icon">🔍</span>' +
            '<input type="search" placeholder="Пошук у вікі..." aria-label="Пошук" id="mobile-search-input">' +
        '</div>';
    document.body.insertBefore(topbar, document.body.firstChild);
    // Прив'язуємо мобільний пошук до рідного MediaWiki пошуку
    var mobileSearchInput = topbar.querySelector('#mobile-search-input');
    if (mobileSearchInput) {
        mobileSearchInput.addEventListener('keydown', function(e) {
            if (e.key === 'Enter') {
                var q = mobileSearchInput.value.trim();
                if (q) {
                    var searchUrl = mw.config.get('wgScript') + '?title=Special:Search&search=' + encodeURIComponent(q);
                    window.location.href = searchUrl;
                }
            }
        });
    }
    /* ── Нижній таббар ── */
    var bottomNav = document.createElement('nav');
    bottomNav.className = 'mobile-bottom-nav';
    bottomNav.setAttribute('aria-label', 'Мобільна навігація');
    // Збираємо дані з оригінального меню користувача
    var userLinks = [];
    var userName = mw.config.get('wgUserName');
    var isLoggedIn = !!userName;
    var articlePath = mw.config.get('wgArticlePath');
    if (isLoggedIn) {
        userLinks = [
            { icon: '🏠', label: 'Головна', href: articlePath.replace('$1', 'Головна_сторінка'), id: 'home' },
            { icon: '☰', label: 'Меню', href: '#', id: 'menu', action: 'toggleNav' },
            { icon: '👤', label: userName.split(' ')[0], href: articlePath.replace('$1', 'Користувач:' + encodeURIComponent(userName)), id: 'user' },
            { icon: '⚙️', label: 'Налаш.', href: articlePath.replace('$1', 'Special:Preferences'), id: 'prefs' },
            { icon: '↩️', label: 'Вийти', href: mw.config.get('wgScript') + '?title=Special:UserLogout&returnto=Головна_сторінка', id: 'logout' },
        ];
    } else {
        userLinks = [
            { icon: '🏠', label: 'Головна', href: articlePath.replace('$1', 'Головна_сторінка'), id: 'home' },
            { icon: '☰', label: 'Меню', href: '#', id: 'menu', action: 'toggleNav' },
            { icon: '🔍', label: 'Пошук', href: articlePath.replace('$1', 'Special:Search'), id: 'search' },
            { icon: '🔑', label: 'Увійти', href: articlePath.replace('$1', 'Special:UserLogin'), id: 'login' },
        ];
    }
    // Визначаємо активний пункт
    var currentPage = mw.config.get('wgPageName');
    var itemsHtml = '<div class="mobile-bottom-nav-items">';
    userLinks.forEach(function(link) {
        var isActive = '';
        if (link.id === 'home' && currentPage === 'Головна_сторінка') isActive = ' active';
        if (link.action === 'toggleNav') {
            itemsHtml += '<button class="mobile-bottom-nav-item menu-btn' + isActive + '" data-action="toggleNav" aria-label="' + link.label + '">' +
                '<span class="mobile-bottom-nav-icon">' + link.icon + '</span>' +
                '<span class="mobile-bottom-nav-label">' + link.label + '</span>' +
            '</button>';
        } else {
            itemsHtml += '<a class="mobile-bottom-nav-item' + isActive + '" href="' + link.href + '" aria-label="' + link.label + '">' +
                '<span class="mobile-bottom-nav-icon">' + link.icon + '</span>' +
                '<span class="mobile-bottom-nav-label">' + mw.html.escape(link.label) + '</span>' +
            '</a>';
        }
    });
    itemsHtml += '</div>';
    bottomNav.innerHTML = itemsHtml;
    document.body.appendChild(bottomNav);
    /* ── Логіка відкриття/закриття бокового меню ── */
     function openMenu() {
     function openMenu() {
         document.body.classList.add('mobile-nav-open');
         document.body.classList.add('mobile-nav-open');
         overlay.classList.add('open');
         overlay.classList.add('open');
         btn.innerHTML = '✕';
         var menuBtn = bottomNav.querySelector('[data-action="toggleNav"]');
         btn.setAttribute('aria-label', 'Закрити меню');
         if (menuBtn) {
            menuBtn.querySelector('.mobile-bottom-nav-icon').textContent = '✕';
            menuBtn.classList.add('active');
        }
     }
     }


Рядок 62: Рядок 162:
         document.body.classList.remove('mobile-nav-open');
         document.body.classList.remove('mobile-nav-open');
         overlay.classList.remove('open');
         overlay.classList.remove('open');
         btn.innerHTML = '☰';
         var menuBtn = bottomNav.querySelector('[data-action="toggleNav"]');
         btn.setAttribute('aria-label', 'Відкрити меню');
         if (menuBtn) {
            menuBtn.querySelector('.mobile-bottom-nav-icon').textContent = '☰';
            menuBtn.classList.remove('active');
        }
     }
     }


     btn.addEventListener('click', function() {
     bottomNav.addEventListener('click', function(e) {
         if (document.body.classList.contains('mobile-nav-open')) {
         var btn = e.target.closest('[data-action="toggleNav"]');
            closeMenu();
        if (btn) {
        } else {
            e.preventDefault();
            openMenu();
            if (document.body.classList.contains('mobile-nav-open')) {
                closeMenu();
            } else {
                openMenu();
            }
         }
         }
     });
     });
Рядок 76: Рядок 183:
     overlay.addEventListener('click', closeMenu);
     overlay.addEventListener('click', closeMenu);


    // Закрити при натисканні Escape
     document.addEventListener('keydown', function(e) {
     document.addEventListener('keydown', function(e) {
         if (e.key === 'Escape') closeMenu();
         if (e.key === 'Escape') closeMenu();
     });
     });


    // Закрити при зміні розміру вікна (якщо стало більше 1100px)
     window.addEventListener('resize', function() {
     window.addEventListener('resize', function() {
         if (window.innerWidth > 1100) closeMenu();
         if (window.innerWidth > 1100) closeMenu();
     });
     });
});
});


/* ══════════════════════════════════════════════
/* ══════════════════════════════════════════════

Версія за 22:55, 24 березня 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 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;">' + (siteName.charAt(0) || '🏛') + '</span>';

    topbar.innerHTML =
        '<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">' +
            '<span class="mobile-topbar-search-icon">🔍</span>' +
            '<input type="search" placeholder="Пошук у вікі..." aria-label="Пошук" id="mobile-search-input">' +
        '</div>';

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

    // Прив'язуємо мобільний пошук до рідного MediaWiki пошуку
    var mobileSearchInput = topbar.querySelector('#mobile-search-input');
    if (mobileSearchInput) {
        mobileSearchInput.addEventListener('keydown', function(e) {
            if (e.key === 'Enter') {
                var q = mobileSearchInput.value.trim();
                if (q) {
                    var searchUrl = mw.config.get('wgScript') + '?title=Special:Search&search=' + encodeURIComponent(q);
                    window.location.href = searchUrl;
                }
            }
        });
    }

    /* ── Нижній таббар ── */
    var bottomNav = document.createElement('nav');
    bottomNav.className = 'mobile-bottom-nav';
    bottomNav.setAttribute('aria-label', 'Мобільна навігація');

    // Збираємо дані з оригінального меню користувача
    var userLinks = [];
    var userName = mw.config.get('wgUserName');
    var isLoggedIn = !!userName;
    var articlePath = mw.config.get('wgArticlePath');

    if (isLoggedIn) {
        userLinks = [
            { icon: '🏠', label: 'Головна', href: articlePath.replace('$1', 'Головна_сторінка'), id: 'home' },
            { icon: '☰', label: 'Меню', href: '#', id: 'menu', action: 'toggleNav' },
            { icon: '👤', label: userName.split(' ')[0], href: articlePath.replace('$1', 'Користувач:' + encodeURIComponent(userName)), id: 'user' },
            { icon: '⚙️', label: 'Налаш.', href: articlePath.replace('$1', 'Special:Preferences'), id: 'prefs' },
            { icon: '↩️', label: 'Вийти', href: mw.config.get('wgScript') + '?title=Special:UserLogout&returnto=Головна_сторінка', id: 'logout' },
        ];
    } else {
        userLinks = [
            { icon: '🏠', label: 'Головна', href: articlePath.replace('$1', 'Головна_сторінка'), id: 'home' },
            { icon: '☰', label: 'Меню', href: '#', id: 'menu', action: 'toggleNav' },
            { icon: '🔍', label: 'Пошук', href: articlePath.replace('$1', 'Special:Search'), id: 'search' },
            { icon: '🔑', label: 'Увійти', href: articlePath.replace('$1', 'Special:UserLogin'), id: 'login' },
        ];
    }

    // Визначаємо активний пункт
    var currentPage = mw.config.get('wgPageName');

    var itemsHtml = '<div class="mobile-bottom-nav-items">';
    userLinks.forEach(function(link) {
        var isActive = '';
        if (link.id === 'home' && currentPage === 'Головна_сторінка') isActive = ' active';

        if (link.action === 'toggleNav') {
            itemsHtml += '<button class="mobile-bottom-nav-item menu-btn' + isActive + '" data-action="toggleNav" aria-label="' + link.label + '">' +
                '<span class="mobile-bottom-nav-icon">' + link.icon + '</span>' +
                '<span class="mobile-bottom-nav-label">' + link.label + '</span>' +
            '</button>';
        } else {
            itemsHtml += '<a class="mobile-bottom-nav-item' + isActive + '" href="' + link.href + '" aria-label="' + link.label + '">' +
                '<span class="mobile-bottom-nav-icon">' + link.icon + '</span>' +
                '<span class="mobile-bottom-nav-label">' + mw.html.escape(link.label) + '</span>' +
            '</a>';
        }
    });
    itemsHtml += '</div>';

    bottomNav.innerHTML = itemsHtml;
    document.body.appendChild(bottomNav);

    /* ── Логіка відкриття/закриття бокового меню ── */
    function openMenu() {
        document.body.classList.add('mobile-nav-open');
        overlay.classList.add('open');
        var menuBtn = bottomNav.querySelector('[data-action="toggleNav"]');
        if (menuBtn) {
            menuBtn.querySelector('.mobile-bottom-nav-icon').textContent = '✕';
            menuBtn.classList.add('active');
        }
    }

    function closeMenu() {
        document.body.classList.remove('mobile-nav-open');
        overlay.classList.remove('open');
        var menuBtn = bottomNav.querySelector('[data-action="toggleNav"]');
        if (menuBtn) {
            menuBtn.querySelector('.mobile-bottom-nav-icon').textContent = '☰';
            menuBtn.classList.remove('active');
        }
    }

    bottomNav.addEventListener('click', function(e) {
        var btn = e.target.closest('[data-action="toggleNav"]');
        if (btn) {
            e.preventDefault();
            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();
    });
});


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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

                var imgName = extractImageName(content);

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

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

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

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

            results.forEach(function(item) {
                var thumbHtml = item.imgSrc
                    ? '<img class="random-article-thumb" src="' + item.imgSrc + '" alt="">'
                    : '<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);
    });
});