Увага: Після публікування слід очистити кеш браузера, щоб побачити зміни.

  • Firefox / Safari: тримайте Shift, коли натискаєте Оновити, або натисніть Ctrl-F5 чи Ctrl-Shift-R (⌘-R на Apple Mac)
  • Google Chrome: натисніть Ctrl-Shift-R (⌘-Shift-R на Apple Mac)
  • Internet Explorer / Edge: тримайте Ctrl, коли натискаєте Оновити, або натисніть Ctrl-F5
  • Opera: натисніть Ctrl-F5
// ============================================================
// MediaWiki:Common.js — Mafia Closed Circle — ФІНАЛЬНА ВЕРСІЯ
// ============================================================

// ============================================================
// 1. RANDOM ARTICLES
// ============================================================
$(document).ready(function () {
    var apiUrl = mw.config.get('wgScriptPath') + '/api.php';
    $.getJSON(apiUrl, {
        action: 'query', format: 'json', list: 'random',
        rnnamespace: '0', rnlimit: '5'
    }, function (data) {
        var html = '';
        $.each(data.query.random, function (i, article) {
            html += '<div class="random-article-preview"><h2><a href="/wiki/'
                + encodeURIComponent(article.title) + '">' + article.title + '</a></h2></div>';
        });
        $('#random-articles-container').html(html);
    });
});

// ============================================================
// 2. L-BOX NAVIGATION
// document.getElementById — коректно обробляє кирилицю
// ============================================================
$(function () {
    var $lbox = $('.l-box');
    if ($lbox.length === 0) return;

    var $items = $lbox.find('.l-box-item');

    function buildSectionMap() {
        var map = [];
        $items.each(function () {
            var target = $(this).data('target');
            if (target === 'top') {
                map.push({ $item: $(this), top: 0 });
            } else {
                var el = document.getElementById(target);
                if (el) {
                    var $el = $(el);
                    var $heading = $el.closest('h2, h3, h4').length
                        ? $el.closest('h2, h3, h4') : $el;
                    map.push({ $item: $(this), top: $heading.offset().top });
                }
            }
        });
        map.sort(function (a, b) { return a.top - b.top; });
        return map;
    }

    function updateActive(map) {
        var scrollY = $(window).scrollTop() + 120;
        var current = null;
        for (var i = 0; i < map.length; i++) {
            if (map[i].top <= scrollY) current = map[i].$item;
        }
        $items.removeClass('active');
        if (current) current.addClass('active');
    }

    $items.on('click', function () {
        var target = $(this).data('target');
        $items.removeClass('active');
        $(this).addClass('active');

        // Якщо активна вкладка ігор — перемикаємо на профіль спочатку
        var $gamesTab = $('.player-tab[data-tab="games"]');
        var gamesActive = $gamesTab.length && $gamesTab.hasClass('active');
        if (gamesActive && target !== 'top') {
            activatePlayerTab('profile');
        }

        var delay = gamesActive ? 60 : 0;
        setTimeout(function () {
            if (target === 'top') {
                $('html, body').animate({ scrollTop: 0 }, 280);
            } else {
                var el = document.getElementById(target);
                if (el) {
                    var $el = $(el);
                    var $heading = $el.closest('h2, h3, h4').length
                        ? $el.closest('h2, h3, h4') : $el;
                    $('html, body').animate({ scrollTop: $heading.offset().top - 78 }, 280);
                }
            }
        }, delay);
    });

    var sectionMap = buildSectionMap();

    $(document).on('mcc:content-loaded', function () {
        sectionMap = buildSectionMap();
        updateActive(sectionMap);
    });

    var ticking = false;
    $(window).on('scroll', function () {
        if (!ticking) {
            window.requestAnimationFrame(function () {
                updateActive(sectionMap);
                ticking = false;
            });
            ticking = true;
        }
    });

    $(window).on('resize', function () {
        sectionMap = buildSectionMap();
        updateActive(sectionMap);
    });

    setTimeout(function () {
        sectionMap = buildSectionMap();
        updateActive(sectionMap);
    }, 200);
});

// ============================================================
// 3. PROFILE ICONS — клік + inactive + розгортання <p>
// ============================================================
$(document).ready(function () {
    // Розгортаємо <p> яку MediaWiki вставляє всередину grid
    function fixProfileGrid() {
        $('.profile-links-icons').each(function () {
            var $wrap = $(this);
            var $p = $wrap.find('> p');
            if ($p.length) {
                $p.children().appendTo($wrap);
                $p.remove();
            }
            $wrap.css({ display: 'grid', 'grid-template-columns': 'repeat(4, 1fr)', gap: '0' });
            $wrap.find('.profile-icon').css({
                display: 'flex', 'align-items': 'center', 'justify-content': 'center',
                padding: '13px 4px', float: 'none', width: 'auto',
                'min-width': '0', overflow: 'hidden',
                'border-right': '1px solid rgba(255,255,255,0.06)'
            });
            $wrap.find('.profile-icon:last-child').css('border-right', 'none');
            $wrap.find('.profile-icon img, .profile-icon .mw-file-element').css({
                width: '22px', height: '22px', 'max-width': '22px',
                'object-fit': 'contain', display: 'block'
            });
            $wrap.find('.profile-icon > span, .profile-icon .mw-default-size').css({
                display: 'flex', 'align-items': 'center',
                'justify-content': 'center', 'line-height': '0'
            });
        });
    }
    fixProfileGrid();
    setTimeout(fixProfileGrid, 400);

    // Клік + inactive
    $('.profile-icon').each(function () {
        var $icon = $(this);
        var url = ($icon.attr('data-url') || '').trim();
        if (url) {
            $icon.css('cursor', 'pointer');
            $icon.on('click', function () { window.open(url, '_blank'); });
        } else {
            $icon.addClass('inactive');
        }
    });
});

// ============================================================
// 4. STATS OVERLAY НА ФОТО ГРАВЦЯ В R-BOX
// ============================================================
$(function () {
    var $rbox = $('.r-box');
    if ($rbox.length === 0) return;

    var wins = '', losses = '', games = '';
    $rbox.find('table tr').each(function () {
        var label = $(this).find('th').text().trim().toLowerCase();
        var val   = $(this).find('td').text().trim();
        if (label.indexOf('офіційних') !== -1 || label.indexOf('ігор') !== -1) {
            var m = val.match(/\((\d+)[^\d]+(\d+)\)/);
            if (m) { wins = m[1]; losses = m[2]; }
            var total = parseInt(wins || 0) + parseInt(losses || 0);
            if (total > 0) games = total;
        }
    });

    if (games && wins && losses) {
        var $figure = $rbox.find('figure');
        if ($figure.length && !$figure.find('.rp-stats-overlay').length) {
            $figure.append(
                '<div class="rp-stats-overlay">'
                + '<div class="rp-stat-box"><span class="rp-sv">' + games  + '</span><span class="rp-sl">Ігор</span></div>'
                + '<div class="rp-stat-box"><span class="rp-sv">' + wins   + '</span><span class="rp-sl">Перемог</span></div>'
                + '<div class="rp-stat-box"><span class="rp-sv">' + losses + '</span><span class="rp-sl">Поразок</span></div>'
                + '</div>'
            );
        }
    }
});

// ============================================================
// 5. ДИНАМІЧНІ ПОСИЛАННЯ НА ГОЛОВНІЙ
// ============================================================
$(document).ready(function () {
    if (!$('body').hasClass('page-Головна_сторінка')) return;

    var block1 = [{ title: 'Фінал Року', url: '/index.php/Фінал_Року' }];
    var block2 = [
        { title: 'Перша статистика', url: '/index.php/Перша_статистика' },
        { title: 'Період',           url: '/index.php/Період' },
        { title: 'Друга статистика', url: '/index.php/Статистика' }
    ];
    var block3 = [
        { title: 'Mafia Closed Cup I',        url: '/index.php/Mafia_Closed_Cup_I' },
        { title: 'Mafia Closed Cup I Online', url: '/index.php/Mafia_Closed_Cup_I_Online' },
        { title: 'My Closest Circle I',       url: '/index.php/My_Closest_Circle_I' }
    ];

    function rand(arr) { return arr[Math.floor(Math.random() * arr.length)]; }

    var $b = $('.home__block-image-block p');
    if ($b.length >= 3) {
        [rand(block1), rand(block2), rand(block3)].forEach(function (l, i) {
            $b.eq(i).html('<a href="' + l.url + '">' + l.title + '</a>');
        });
    }
});

// ============================================================
// 6. PLAYER TABS + LAZY LOADING
// ============================================================

// Глобальна функція перемикання табу (використовується і в l-box)
function activatePlayerTab(tabId) {
    var $tabs     = $('.player-tab');
    var $contents = $('.player-tab-content');
    var $rbox     = $('.r-box');

    $tabs.removeClass('active');
    $contents.removeClass('active');
    $tabs.filter('[data-tab="' + tabId + '"]').addClass('active');
    $('#tab-' + tabId).addClass('active');

    if ($(window).width() <= 768) {
        if (tabId === 'games') $rbox.slideUp(200);
        else                   $rbox.slideDown(200);
    }
}

$(function () {
    var $tabs = $('.player-tab');
    if ($tabs.length === 0) return;

    $tabs.on('click', function () {
        var tabId = $(this).data('tab');
        activatePlayerTab(tabId);

        if (tabId === 'games') {
            var $content = $('#tab-games');
            if ($content.data('loaded')) return;

            var playerName = $content.data('player');
            if (!playerName) return;

            $content.html('<div class="tab-loader">Завантаження...</div>');

            $.ajax({
                url: mw.config.get('wgScriptPath') + '/api.php',
                data: {
                    action: 'expandtemplates', format: 'json',
                    text: '{{#invoke:FetchData|player_games|player=' + playerName + '}}',
                    prop: 'wikitext'
                },
                dataType: 'json',
                success: function (response) {
                    if (!response.expandtemplates || !response.expandtemplates.wikitext) return;
                    $.ajax({
                        url: mw.config.get('wgScriptPath') + '/api.php',
                        data: {
                            action: 'parse', format: 'json',
                            text: response.expandtemplates.wikitext,
                            contentmodel: 'wikitext',
                            disablelimitreport: true
                        },
                        dataType: 'json',
                        success: function (r) {
                            if (!r.parse || !r.parse.text) return;
                            $content.html(r.parse.text['*']);
                            $content.data('loaded', true);

                            var $table = $content.find('table.sortable, table.wikitable');
                            $table.tablesorter();
                            injectGamesFilters($content, $table, playerName);
                            applyWinrateColors($content);
                            wrapWideTables($content);
                            applyRolePills($content);
                            $(document).trigger('mcc:content-loaded');
                        },
                        error: function () {
                            $content.html('<p style="color:#ff7777;text-align:center;padding:20px">Помилка завантаження.</p>');
                        }
                    });
                },
                error: function () {
                    $content.html('<p style="color:#ff7777;text-align:center;padding:20px">Помилка завантаження.</p>');
                }
            });
        }
    });

    $(window).on('resize', function () {
        if ($(window).width() > 768) $('.r-box').show();
    });
});

// ============================================================
// 7. ФІЛЬТРИ НАД ТАБЛИЦЕЮ ІГОР
// ============================================================
function injectGamesFilters($container, $table) {
    if (!$table.length) return;
    if ($container.find('.mcc-games-filters').length) return;

    var events = [];
    $table.find('tbody tr').each(function () {
        var ev = $(this).find('td').eq(0).text().trim();
        if (ev && events.indexOf(ev) === -1) events.push(ev);
    });

    var opts = '<option value="">Всі події</option>';
    events.forEach(function (e) { opts += '<option value="' + e + '">' + e + '</option>'; });

    $table.before(
        '<div class="mcc-games-filters">'
        + '<div class="mcc-filter-group"><span class="mcc-filter-label">Подія</span>'
        +   '<select class="mcc-filter-select" id="mcc-f-event">' + opts + '</select></div>'
        + '<div class="mcc-filter-group"><span class="mcc-filter-label">Роль</span>'
        +   '<select class="mcc-filter-select" id="mcc-f-role">'
        +   '<option value="">Всі ролі</option><option value="Мир">Мирний</option>'
        +   '<option value="Шер">Шериф</option><option value="Маф">Мафія</option>'
        +   '<option value="Дон">Дон</option></select></div>'
        + '<div class="mcc-filter-group"><span class="mcc-filter-label">Результат</span>'
        +   '<select class="mcc-filter-select" id="mcc-f-result">'
        +   '<option value="">Всі</option><option value="В">Перемога</option>'
        +   '<option value="П">Поразка</option></select></div>'
        + '<div class="mcc-filter-group mcc-duration-group">'
        +   '<span class="mcc-filter-label">Макс. тривалість</span>'
        +   '<div class="mcc-slider-wrap">'
        +     '<input type="range" class="mcc-duration-range" id="mcc-f-dur" min="20" max="70" value="70" step="1">'
        +     '<span class="mcc-slider-val" id="mcc-dur-val">70:00</span>'
        +   '</div></div>'
        + '<span class="mcc-filter-count" id="mcc-games-count"></span>'
        + '</div>'
    );

    function toMins(s) {
        s = (s || '').trim();
        var m1 = s.match(/^(\d+):(\d+)$/);
        if (m1) return +m1[1] + +m1[2] / 60;
        var m2 = s.match(/(\d+)\s*хв\s*(\d+)/);
        if (m2) return +m2[1] + +m2[2] / 60;
        return 999;
    }

    function filter() {
        var ev  = $('#mcc-f-event').val();
        var rol = $('#mcc-f-role').val();
        var res = $('#mcc-f-result').val();
        var dur = +$('#mcc-f-dur').val();
        var n = 0;
        $table.find('tbody tr').each(function () {
            var td = $(this).find('td');
            var show = (!ev  || td.eq(0).text().trim().indexOf(ev)  !== -1)
                    && (!rol || td.eq(1).text().trim().indexOf(rol) !== -1)
                    && (!res || td.eq(3).text().trim().indexOf(res) !== -1)
                    && toMins(td.eq(2).text()) <= dur;
            $(this).toggle(show);
            if (show) n++;
        });
        $('#mcc-games-count').text(n + ' ігор');
    }

    $('#mcc-f-dur').on('input', function () {
        var v = +$(this).val();
        $('#mcc-dur-val').text(v + ':00');
        $(this).css('background-size', ((v - 20) / 50 * 100) + '% 100%');
        filter();
    });

    $container.find('.mcc-filter-select').on('change', filter);

    var total = $table.find('tbody tr').length;
    $('#mcc-games-count').text(total + ' ігор');
    $('#mcc-f-dur').css('background-size', '100% 100%');
}

// ============================================================
// 8. ROLE PILLS
// ============================================================
function applyRolePills($context) {
    var $root = $context || $(document);
    var roleMap = {
        'Мир': { bg:'rgba(76,175,125,0.12)',  color:'#7dd4a6', border:'rgba(76,175,125,0.22)' },
        'Шер': { bg:'rgba(91,143,255,0.12)',   color:'#7da8ff', border:'rgba(91,143,255,0.22)' },
        'Маф': { bg:'rgba(200,76,76,0.12)',    color:'#e08888', border:'rgba(200,76,76,0.22)'  },
        'Дон': { bg:'rgba(255,215,0,0.10)',    color:'#ffd700', border:'rgba(255,215,0,0.22)'  }
    };

    $root.find('.wikitable tbody td').each(function () {
        var $cell = $(this);
        var $span = $cell.find('span').filter(function () {
            return ($(this).attr('style') || '').indexOf('color') !== -1;
        });
        if (!$span.length) return;
        var text  = $span.text().trim();
        var style = roleMap[text];
        if (!style || $span.hasClass('mcc-pill-done')) return;
        $span.addClass('mcc-pill-done').css({
            display:'inline-block', padding:'2px 10px', borderRadius:'4px',
            fontSize:'12.5px', fontWeight:'600', fontFamily:"'Manrope',sans-serif",
            background: style.bg, color: style.color, border:'1px solid '+style.border
        });
    });
}

$(function () { applyRolePills(); });
$(document).on('mcc:content-loaded', function () { applyRolePills(); });

// ============================================================
// 9. АНІМАЦІЯ РЯДКІВ ПРИ СОРТУВАННІ
// ============================================================
$(function () {
    $(document).on('sortEnd', 'table.wikitable', function () {
        var $t = $(this);
        $t.addClass('mcc-sorting').removeClass('mcc-sorted');
        setTimeout(function () {
            $t.removeClass('mcc-sorting').addClass('mcc-sorted');
            setTimeout(function () { $t.removeClass('mcc-sorted'); }, 600);
        }, 20);
    });
});

// ============================================================
// 10. ГОРИЗОНТАЛЬНИЙ СКРОЛ ДЛЯ ШИРОКИХ ТАБЛИЦЬ
// ============================================================
function wrapWideTables($context) {
    var $root = $context || $(document);

    function wrap($table) {
        if ($table.closest('.mcc-scroll-inner').length) return;
        $table.wrap('<div class="mcc-scroll-inner"></div>');
        $table.closest('.mcc-scroll-inner').wrap('<div class="mcc-scroll-outer"></div>');
        var $inner = $table.closest('.mcc-scroll-inner');
        var $outer = $inner.closest('.mcc-scroll-outer');
        function check() {
            $outer.toggleClass('mcc-no-fade',
                $inner[0].scrollLeft + $inner[0].clientWidth >= $inner[0].scrollWidth - 4);
        }
        $inner.on('scroll', check);
        check();
    }

    $root.find('.wikitable.wide-table, .wikitable.mcc-wide, .wikitable.full-width').each(function () {
        wrap($(this));
    });

    $root.find('.wikitable').each(function () {
        var $t = $(this);
        if ($t.closest('.mcc-scroll-inner, .r-box, .tournament-box').length) return;
        if ($t.find('thead tr:first th').length > 8) {
            $t.addClass('mcc-wide-table');
            wrap($t);
        }
    });
}

$(function () { wrapWideTables(); });

// ============================================================
// 11. ВІНРЕЙТ — кольорові класи
// ============================================================
function applyWinrateColors($context) {
    var $root = $context || $(document);
    $root.find('.wikitable tbody td').each(function () {
        var $c = $(this);
        if ($c.hasClass('wr-hi') || $c.hasClass('wr-lo')) return;
        var m = $c.text().trim().match(/^(\d+(?:\.\d+)?)%$/);
        if (!m) return;
        var v = parseFloat(m[1]);
        if      (v >= 55) $c.addClass('wr-hi');
        else if (v <= 33) $c.addClass('wr-lo');
    });
}

$(function () { applyWinrateColors(); });

// ============================================================
// 12. PLAYER TABS — "(42)" → стилізований badge
// ============================================================
$(function () {
    $('.player-tab').each(function () {
        var $tab = $(this);
        var m = $tab.text().match(/\((\d+)\)/);
        if (!m) return;
        $tab.text($tab.text().replace(/\s*\(\d+\)/, '').trim());
        $tab.append('<span class="mcc-tab-cnt">' + m[1] + '</span>');
    });
});

// ============================================================
// 13. СЕЗОНИ — "Чемпіон" синього кольору
// ============================================================
$(function () {
    function applySeasonColors($ctx) {
        ($ctx || $(document)).find('.wikitable tbody td').each(function () {
            var t = $(this).text().trim();
            if (t === 'Чемпіон' || t === '♔ Чемпіон') {
                $(this).css({ color: '#7ab8ff', fontWeight: '700' });
            }
        });
    }
    applySeasonColors();
    $(document).on('mcc:content-loaded', function () { applySeasonColors(); });
});

// ============================================================
// 14. NAV <pre> — розгортаємо pre всередині навігації
// ============================================================
$(function () {
    var sel = '.tournament-nav, .series-nav, .player-nav, .championship-nav';
    $(sel).each(function () {
        var $nav = $(this);
        var $pre = $nav.find('pre');
        if (!$pre.length) return;
        $pre.contents().each(function () { $nav.append($(this).clone()); });
        $pre.remove();
    });
});

// ============================================================
// 15. МОБІЛЬНИЙ ПОШУК
// ============================================================
$(function () {
    if ($(window).width() > 768) return;
    if ($('.mobile-search-btn').length) return;

    var $btn = $('<div class="mobile-search-btn">'
        + '<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="#fff" stroke-width="2">'
        + '<circle cx="11" cy="11" r="8"/><path d="m21 21-4.35-4.35"/></svg></div>');

    var $overlay = $('<div class="mobile-search-overlay">'
        + '<input type="text" placeholder="Пошук..." autocomplete="off">'
        + '<div class="mobile-search-close">×</div></div>');

    $('.minerva-header .branding-box').after($btn);
    $('body').append($overlay);

    var $input = $overlay.find('input');
    var $close = $overlay.find('.mobile-search-close');

    $btn.on('click', function (e) {
        e.preventDefault(); e.stopPropagation();
        $overlay.addClass('active');
        setTimeout(function () { $input.focus(); }, 100);
    });
    $close.on('click', function () { $overlay.removeClass('active'); $input.val(''); });
    $input.on('keydown', function (e) {
        if (e.keyCode === 13) {
            var q = $input.val().trim();
            if (q) window.location.href = '/index.php?title=Спеціальна:Пошук&search=' + encodeURIComponent(q);
        }
        if (e.keyCode === 27) { $overlay.removeClass('active'); $input.val(''); }
    });
    $overlay.on('click', function (e) {
        if (e.target === this) { $overlay.removeClass('active'); $input.val(''); }
    });
});

// ============================================================
// 16. БЛОКУВАННЯ MINERVA SEARCH OVERLAY (ДЕСКТОП)
// ============================================================
$(function () {
    if ($(window).width() <= 768) return;

    var $searchInput = $('#searchInput');
    if ($searchInput.length === 0) return;

    setTimeout(function () {
        $searchInput.attr('placeholder', 'Пошук...');
        var $new = $searchInput.clone(false);
        $searchInput.replaceWith($new);
        $searchInput = $new;

        $searchInput.prop('readonly', false).removeAttr('readonly')
            .removeClass('skin-minerva-search-trigger');

        $searchInput.on('focus click', function (e) {
            e.stopPropagation();
            $('body').removeClass('overlay-enabled search-enabled');
            $('.overlay, .search-overlay').hide();
            if (window.location.hash === '#/search')
                history.replaceState(null, null, window.location.pathname);
        });

        $searchInput.on('keydown', function (e) {
            if (e.which === 13) {
                e.preventDefault();
                var q = $(this).val().trim();
                if (q) window.location.href = '/index.php?title=Спеціальна:Пошук&search=' + encodeURIComponent(q);
                return false;
            }
        });
    }, 100);

    $(window).on('hashchange', function () {
        if (window.location.hash === '#/search') {
            history.replaceState(null, null, window.location.pathname);
            $('body').removeClass('overlay-enabled search-enabled');
            $('.overlay, .search-overlay').hide();
        }
    });

    if (window.location.hash === '#/search')
        history.replaceState(null, null, window.location.pathname);
});

// ============================================================
// 17. BANNER SEARCH
// ============================================================
$(function () {
    var $container = $('#bannerSearchContainer');
    if (!$container.length) return;

    var $input = $('<input>', { type:'text', id:'bannerSearchInput', placeholder:'Пошук MCC...' });
    var $btn   = $('<button>', { id:'bannerSearchBtn', text:'Пошук' });
    $container.append($input).append($btn);

    function doSearch() {
        var q = $input.val().trim();
        if (q) window.location.href = '/index.php?title=Спеціальна:Пошук&search=' + encodeURIComponent(q);
    }
    $btn.on('click', doSearch);
    $input.on('keydown', function (e) { if (e.keyCode === 13) { e.preventDefault(); doSearch(); } });
});