Toggle menu
Toggle preferences menu
Toggle personal menu
Not logged in
Your IP address will be publicly visible if you make any edits.

MediaWiki:Common.js: Difference between revisions

MediaWiki interface page
No edit summary
No edit summary
Line 662: Line 662:
     });
     });


});
/* ================================================================
  BRACKET CONNECTOR LINES — SVG overlay drawn after layout
  Measures actual card positions so lines always hit card centres
  ================================================================ */
$(function () {
    function drawBracketConnectors() {
        /* ── GSL connectors ──────────────────────────────────── */
        $('.bk-gsl').each(function () {
            var $root    = $(this);
            var rootOff  = $root.offset();
            var rootW    = $root.outerWidth();
            var rootH    = $root.outerHeight();
            /* Remove old SVG if redrawing */
            $root.find('.bk-connector-svg').remove();
            var svgNS = 'http://www.w3.org/2000/svg';
            var svg  = document.createElementNS(svgNS, 'svg');
            svg.setAttribute('class', 'bk-connector-svg');
            svg.setAttribute('width',  rootW);
            svg.setAttribute('height', rootH);
            svg.style.position = 'absolute';
            svg.style.top  = '0';
            svg.style.left = '0';
            function midY($el) {
                if (!$el.length) return 0;
                var off = $el.offset();
                return (off.top - rootOff.top) + $el.outerHeight() / 2;
            }
            function midX($el, side) {
                if (!$el.length) return 0;
                var off = $el.offset();
                if (side === 'right') return (off.left - rootOff.left) + $el.outerWidth();
                return off.left - rootOff.left;
            }
            function line(x1, y1, x2, y2) {
                var l = document.createElementNS(svgNS, 'line');
                l.setAttribute('x1', Math.round(x1));
                l.setAttribute('y1', Math.round(y1));
                l.setAttribute('x2', Math.round(x2));
                l.setAttribute('y2', Math.round(y2));
                svg.appendChild(l);
            }
            var $col1 = $root.find('.bk-gsl-col1');
            var $col2 = $root.find('.bk-gsl-col2');
            var $col3 = $root.find('.bk-gsl-col3');
            var $q1  = $col1.find('.bk-gsl-top .bk-match');
            var $elim = $col1.find('.bk-gsl-bot .bk-match');
            var $q2  = $col2.find('.bk-gsl-mid .bk-match');
            var $fin  = $col3.find('.bk-gsl-final .bk-match');
            if ($q1.length && $q2.length) {
                var q1Right  = midX($q1,  'right');
                var q1Mid    = midY($q1);
                var elimRight= midX($elim, 'right');
                var elimMid  = midY($elim);
                var q2Left  = midX($q2,  'left');
                var q2Mid    = midY($q2);
                var midJoinX = q2Left - 10; /* vertical join point */
                /* Q1 horizontal arm → join */
                line(q1Right,  q1Mid,  midJoinX, q1Mid);
                /* Elim horizontal arm → join */
                line(elimRight, elimMid, midJoinX, elimMid);
                /* Vertical join between Q1 and Elim arms */
                line(midJoinX, q1Mid, midJoinX, elimMid);
                /* Horizontal from join midpoint → Q2 left */
                var joinMidY = (q1Mid + elimMid) / 2;
                line(midJoinX, joinMidY, q2Left, joinMidY);
            }
            if ($q2.length && $fin.length) {
                var q2Right = midX($q2,  'right');
                var q2MidY  = midY($q2);
                var finLeft = midX($fin, 'left');
                var finMidY = midY($fin);
                var midX2  = q2Right + (finLeft - q2Right) / 2;
                /* Q2 → midpoint horizontal */
                line(q2Right, q2MidY, midX2, q2MidY);
                /* Vertical drop/rise to Final midY */
                line(midX2, q2MidY, midX2, finMidY);
                /* midpoint → Final left */
                line(midX2, finMidY, finLeft, finMidY);
            }
            $root.prepend(svg);
        });
        /* ── Single Elim connectors ──────────────────────────── */
        $('.bk-single-elim').each(function () {
            var $root  = $(this);
            var rootOff = $root.offset();
            var rootW  = $root.outerWidth();
            var rootH  = $root.outerHeight();
            $root.find('.bk-connector-svg').remove();
            var svgNS = 'http://www.w3.org/2000/svg';
            var svg  = document.createElementNS(svgNS, 'svg');
            svg.setAttribute('class', 'bk-connector-svg');
            svg.setAttribute('width',  rootW);
            svg.setAttribute('height', rootH);
            svg.style.position = 'absolute';
            svg.style.top  = '0';
            svg.style.left = '0';
            $root.find('.has-connector .bk-match').each(function () {
                var $card = $(this);
                var off  = $card.offset();
                var x1    = (off.left - rootOff.left) + $card.outerWidth();
                var y1    = (off.top  - rootOff.top)  + $card.outerHeight() / 2;
                var x2    = x1 + 44;
                var l    = document.createElementNS(svgNS, 'line');
                l.setAttribute('x1', Math.round(x1));
                l.setAttribute('y1', Math.round(y1));
                l.setAttribute('x2', Math.round(x2));
                l.setAttribute('y2', Math.round(y2 || y1));
                svg.appendChild(l);
            });
            $root.prepend(svg);
        });
    }
    /* Draw on load and on window resize */
    setTimeout(drawBracketConnectors, 200);
    $(window).on('resize', function () {
        clearTimeout(window._bkResizeTimer);
        window._bkResizeTimer = setTimeout(drawBracketConnectors, 150);
    });
});
});

Revision as of 01:48, 20 March 2026

/* Any JavaScript here will be loaded for all users on every page load. */

/* ==========================================================
   REMOVE DECIMALS (.0) FROM CARGO TABLES
   ========================================================== */
$(document).ready(function() {
    // Target only cells inside the auto-rank table
    $('.auto-rank td').each(function() {
        var text = $(this).text();
        
        // If the text looks like a number ending in .0 (e.g., "93.0")
        if (/^\d+\.0$/.test(text)) {
            // Replace it with just the integer part
            $(this).text(parseInt(text));
        }
    });
});


/* ==========================================================
   INDIAN CURRENCY FORMATTER (₹ Symbol Version)
   ========================================================== */
$(document).ready(function() {
    $('.indian-currency').each(function() {
        // 1. Get text and clean it (Remove commas AND existing ₹ symbol)
        var rawNum = $(this).text().trim().replace(/,/g, '').replace(/₹/g, '');
        
        // 2. Convert to a real number
        var number = parseFloat(rawNum);
        
        // 3. Check if it's a valid number
        if (!isNaN(number)) {
            // 4. Format to Indian Style (en-IN) - Automatically adds ₹
            var formatted = number.toLocaleString('en-IN', {
                style: 'currency', 
                currency: 'INR', 
                maximumFractionDigits: 0 
            });
            
            // 5. Apply directly (This keeps the ₹ symbol)
            $(this).text(formatted); 
        }
    });
});

/* ========================================================
   UNIVERSAL FILTER SYSTEM (Centralized Logic)
   ======================================================== */
$(function() {
    
    // MASTER FUNCTION: updates the entire wrapper based on current button states
    function refreshWrapperState($wrapper) {
        // 1. Get the current settings
        var activeView = $wrapper.find('.filter-btn[data-filter-type^="view_mode"].active').attr('data-value') || 'overall';
        var activeGroup = ($wrapper.find('.filter-btn[data-filter-type^="group_"].active').attr('data-value') || 'all').toString().trim();
        var filterType = $wrapper.find('.filter-btn[data-filter-type^="view_mode"].active').attr('data-filter-type'); // e.g., view_mode_The Grind

        // 2. Hide all Views (Overall & Matches), then Show the Active One
        $wrapper.find('.filterable-content[data-type^="view_mode"]').hide();
        
        // Find the specific view (e.g., Match 2 table)
        // We use the filterType to ensure we don't accidentally grab a view from a different stage
        var $activeTable = $wrapper.find('.filterable-content[data-type="' + filterType + '"][data-value="' + activeView + '"]');
        $activeTable.fadeIn(100);

        // 3. Apply Group Filter to the rows INSIDE the active table
        // We target ANY row (tr) that has a data-value attribute
        var $rows = $activeTable.find('tr[data-value]');
        
        if (activeGroup === 'all') {
            $rows.show();
        } else {
            $rows.each(function() {
                var $row = $(this);
                var rowGroup = ($row.attr('data-value') || "").toString().trim();
                
                if (rowGroup === activeGroup) {
                    $row.show();
                } else {
                    $row.hide();
                }
            });
        }
    }

    // CLICK HANDLER
    $(document).on('click', '.filter-btn', function() {
        var $btn = $(this);
        var filterType = $btn.attr('data-filter-type'); 
        var value = $btn.attr('data-value');

        // Visual Update (Active State)
        $btn.siblings('.filter-btn').removeClass('active');
        $btn.addClass('active');
        
        // LOGIC A: MASTER STAGE (Big Tabs like "Round 1")
        if (filterType.indexOf('master_stage') !== -1) {
            $('.filterable-content[data-type="' + filterType + '"]').hide();
            $('.filterable-content[data-type="' + filterType + '"][data-value="' + value + '"]').fadeIn(200);
            
            // Optional: When switching stages, trigger a refresh on that stage's wrapper
            var $newStage = $('.filterable-content[data-type="' + filterType + '"][data-value="' + value + '"]');
            var $innerWrapper = $newStage.find('.standings-wrapper');
            if ($innerWrapper.length) refreshWrapperState($innerWrapper);

        // LOGIC B: STANDINGS FILTERS (View or Group)
        } else {
            // Just run the master refresh on the parent wrapper
            var $wrapper = $btn.closest('.standings-wrapper');
            refreshWrapperState($wrapper);
        }
    });

    // AUTO-INIT
    setTimeout(function() {
        if (!$('.filter-btn[data-filter-type="master_stage_selector"].active').length) {
            $('.filter-btn[data-filter-type="master_stage_selector"]').first().click();
        }
    }, 500);
});

/* ==========================================================
   SMART HORIZONTAL SCROLL (Mouse Wheel)
   ========================================================== */
mw.loader.using(['jquery'], function () {
    $(function() {
        $('.standings-wrapper').on('wheel', function(e) {
            var container = this;
            var delta = e.originalEvent.deltaY;

            // Only act if the table is wider than the screen
            if (container.scrollWidth > container.clientWidth) {
                
                // Calculate current scroll position vs max scroll
                var scrollLeft = container.scrollLeft;
                var scrollWidth = container.scrollWidth;
                var clientWidth = container.clientWidth;
                var maxScroll = scrollWidth - clientWidth;
                
                // Check if we are at the edges (allow 1px buffer for browsers)
                var atRightEdge = (scrollLeft >= maxScroll - 1);
                var atLeftEdge = (scrollLeft <= 1);

                // LOGIC:
                // 1. If scrolling RIGHT (delta > 0) and NOT at end -> Scroll Table
                // 2. If scrolling LEFT (delta < 0) and NOT at start -> Scroll Table
                // 3. Otherwise -> Do nothing (Let page scroll naturally)
                
                if ((delta > 0 && !atRightEdge) || (delta < 0 && !atLeftEdge)) {
                    container.scrollLeft += delta;
                    e.preventDefault(); // Stop page scroll ONLY when table is moving
                }
            }
        });
    });
});

/* Active Tier Filter Highlight */
$(function() {
    var urlParams = new URLSearchParams(window.location.search);
    var tier = urlParams.get('tier');
    var $buttons = $('#tier-filters .filter-btn');
    $buttons.removeClass('active');
    if (tier) {
        $('#tier-filters .filter-btn[data-tier="' + tier + '"]').addClass('active');
    } else {
        $buttons.first().addClass('active');
    }
});


/* ==========================================================
   LIVE UPDATE NOTIFIER (Secure Version)
   Checks every 60 seconds if the page has a newer revision.
   ========================================================== */
$(document).ready(function() {
    // Only run on View mode
    if (mw.config.get('wgAction') !== 'view') return;

    var currentRevId = mw.config.get('wgCurRevisionId');
    var pageTitle = mw.config.get('wgPageName');

    function checkForUpdates() {
        new mw.Api().get({
            action: 'query',
            prop: 'info',
            titles: pageTitle,
            indexpageids: 1
        }).done(function(data) {
            var page = data.query.pages[data.query.pageids[0]];
            // If server has a newer ID
            if (page.lastrevid > currentRevId) {
                showUpdateToast();
            }
        });
    }

    function showUpdateToast() {
        // Prevent duplicate buttons
        if ($('#update-notification').length > 0) return;

        // 1. Create the Button Safely (No raw HTML strings)
        var $icon = $('<i>').addClass('fa-solid fa-rotate').css('margin-right', '8px');
        
        var $btn = $('<div>')
            .attr('id', 'update-notification')
            .text(' New updates available. Click to refresh.')
            .prepend($icon)
            .css({
                'position': 'fixed',
                'bottom': '30px',
                'left': '50%',
                'transform': 'translateX(-50%)',
                'background-color': '#00509d',
                'color': 'white',
                'padding': '12px 25px',
                'border-radius': '50px',
                'cursor': 'pointer',
                'box-shadow': '0 4px 15px rgba(0,0,0,0.3)',
                'z-index': '9999',
                'font-family': 'sans-serif',
                'font-weight': 'bold',
                'display': 'flex',
                'align-items': 'center'
            })
            .on('click', function() {
                location.reload();
            });

        // 2. Add to page with animation
        $('body').append($btn);
        $btn.hide().fadeIn(500).css('bottom', '30px'); 
    }

    // Run check every 60 seconds
    setInterval(checkForUpdates, 60000);
});

/* ==========================================================
   CLEAN PAGE TITLES (Fixes H1, Sticky Header, AND Browser Tab)
   Turns "BGMI/Teams/Orangutan" -> "Orangutan"
   ========================================================== */
$(function() {
    var pageTitle = mw.config.get('wgTitle');

    // Only run if we are deep in a structure (contains slash)
    if (pageTitle.indexOf('/') !== -1) {
        // Get the text after the last slash and replace underscores
        var cleanTitle = pageTitle.split('/').pop().replace(/_/g, ' '); 

        // 1. Fix the On-Page Header (H1)
        $('.firstHeading').text(cleanTitle);

        // 2. Fix the Citizen Skin Sticky Header
        $('.citizen-header__title').text(cleanTitle);

        // 3. Fix the Browser Tab Title
        var siteName = mw.config.get('wgSiteName') || 'eSportsAmaze';
        document.title = cleanTitle + ' - ' + siteName;
    }
});


/* ==========================================================
MANUAL AD INJECTION (Safe Mode / Firewall Bypass)
========================================================== */
$(document).ready(function() {
// 1. YOUR AD DETAILS
var clientID = "ca-pub-9380457493130804";
var bottomSlotID = "9418872470";
var topSlotID = "1308895278";

// 2. Build the Bottom/Sidebar Ad Unit (Standard Size)
var $bottomAdContainer = $('<div>')
.addClass('wiki-ad-bottom')
.css({
'margin-top': '20px',
'text-align': 'center',
'min-height': '250px'
});
var $bottomLabel = $('<div>')
.css({ 'font-size': '10px', 'color': '#999', 'margin-bottom': '5px' })
.text('ADVERTISEMENT');
var $bottomIns = $('<ins>')
.addClass('adsbygoogle')
.css('display', 'block')
.attr('data-ad-client', clientID)
.attr('data-ad-slot', bottomSlotID)
.attr('data-ad-format', 'auto')
.attr('data-full-width-responsive', 'true');
$bottomAdContainer.append($bottomLabel, $bottomIns);

// 3. Build the Top Mobile Ad Unit (Horizontal Only)
var $topAdContainer = $('<div>')
  .addClass('wiki-ad-top')
  .css({
    'margin-bottom': '15px',
    'text-align': 'center',
    'height': '70px',
    'max-height': '70px',
    'overflow': 'hidden'
  });

var $topLabel = $('<div>')
  .css({ 'font-size': '10px', 'color': '#999', 'margin-bottom': '3px', 'line-height': '10px' })
  .text('ADVERTISEMENT');

var $topIns = $('<ins>')
  .addClass('adsbygoogle')
  .css({ 'display': 'inline-block', 'width': '320px', 'height': '50px' })
  .attr('data-ad-client', clientID)
  .attr('data-ad-slot', topSlotID);

$topAdContainer.append($topLabel, $topIns);

// 4. Inject into the Page based strictly on device width
var $toc = $('#citizen-toc');
var $footer = $('#catlinks');
var $content = $('#mw-content-text');

if ($(window).width() > 1000) {
// === DESKTOP LOGIC (1 Ad Only) ===
if ($toc.length > 0) {
// If TOC exists, put it after the TOC
$toc.after($bottomAdContainer);
} else {
// If no TOC on desktop, put it at the bottom
if ($footer.length > 0) $footer.before($bottomAdContainer);
else $content.after($bottomAdContainer);
}
// Push AdSense once
try { (adsbygoogle = window.adsbygoogle || []).push({}); } catch (e) { console.log(e); }

} else {
// === MOBILE LOGIC (2 Ads) ===
// Inject Top Ad above content
$content.before($topAdContainer);

// Inject Bottom Ad at the end
if ($footer.length > 0) $footer.before($bottomAdContainer);
else $content.after($bottomAdContainer);

// Push AdSense twice for two ads
try { (adsbygoogle = window.adsbygoogle || []).push({}); } catch (e) { console.log(e); }
try { (adsbygoogle = window.adsbygoogle || []).push({}); } catch (e) { console.log(e); }
}
});


/* ==========================================================
   AUTO TIMEZONE CONVERTER (For Calendar & Schedules)
   Converts elements with <span class="local-time" data-utc="...">
   ========================================================== */
$(function() {
    $('.local-time').each(function() {
        var utcString = $(this).attr('data-utc');
        if (!utcString) return;

        var dateObj = new Date(utcString);
        
        // Check if date is valid
        if (isNaN(dateObj)) return;

        // Format to User's Local Time (e.g., "2:30 PM")
        var localTime = new Intl.DateTimeFormat('default', {
            hour: 'numeric',
            minute: '2-digit',
            timeZoneName: 'short'
        }).format(dateObj);

        // Update the text
        $(this).text(localTime);
    });
});

/* ==========================================================
   INTERACTIVE ESPORTS CALENDAR ENGINE (Stream Button)
   ========================================================== */
$(function() {
    $('.esports-calendar-container').each(function() {
        var $container = $(this);
        var $dataNode = $container.find('.calendar-data');
        if (!$dataNode.length) return;

        var scheduleData = {};
        try { scheduleData = JSON.parse($dataNode.text()); } 
        catch(e) { console.error("Calendar Parse Error", e); return; }

        var allDates = Object.keys(scheduleData).sort();
        if (allDates.length === 0) return;

        var today = new Date();
        var todayStr = today.getFullYear() + "-" + String(today.getMonth()+1).padStart(2,'0') + "-" + String(today.getDate()).padStart(2,'0');
        
        var targetDate = null;
        if (scheduleData[todayStr]) {
            targetDate = todayStr; 
        } else {
            var futureDates = allDates.filter(function(d) { return d > todayStr; });
            if (futureDates.length > 0) {
                targetDate = futureDates[0]; 
            } else {
                targetDate = allDates[allDates.length - 1]; 
            }
        }

        var currentMonth = new Date(targetDate).getMonth();
        var currentYear = new Date(targetDate).getFullYear();

        var $datesGrid = $container.find('.calendar-grid-dates');
        var $monthYearLabel = $container.find('.cal-month-year');
        var $detailsContent = $container.find('.cal-details-content');

        var monthNames = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];

        function formatLocalTime(timeStr) {
            var d;
            if (timeStr.indexOf("T") !== -1) { d = new Date(timeStr); } 
            else { d = new Date("2000-01-01T" + timeStr + ":00Z"); } 
            
            if (isNaN(d)) return timeStr;
            return new Intl.DateTimeFormat('en-US', { hour: 'numeric', minute: '2-digit', hour12: true }).format(d);
        }

        function renderCalendar() {
            $datesGrid.empty();
            $monthYearLabel.text(monthNames[currentMonth] + " " + currentYear);

            var firstDayRaw = new Date(currentYear, currentMonth, 1).getDay();
            var firstDay = (firstDayRaw === 0) ? 6 : firstDayRaw - 1;

            var daysInMonth = new Date(currentYear, currentMonth + 1, 0).getDate();

            for (var i = 0; i < firstDay; i++) { $datesGrid.append('<div class="cal-day empty"></div>'); }

            for (var day = 1; day <= daysInMonth; day++) {
                var dateStr = currentYear + "-" + String(currentMonth + 1).padStart(2, '0') + "-" + String(day).padStart(2, '0');
                var $dayDiv = $('<div class="cal-day"></div>').text(day).attr('data-date', dateStr);

                if (scheduleData[dateStr]) {
                    $dayDiv.addClass('has-events');
                    
                    var dayStages = [...new Set(scheduleData[dateStr].map(function(e){ return e.stage || "Matches"; }))];
                    var stageText = dayStages.length === 1 ? dayStages[0] : dayStages.length + " Stages";
                    $dayDiv.append('<div class="cal-day-stage">' + stageText + '</div>');

                    $dayDiv.on('click', function() {
                        $container.find('.cal-day').removeClass('active');
                        $(this).addClass('active');
                        showDetails($(this).attr('data-date'));
                    });
                }
                $datesGrid.append($dayDiv);
            }
            
            var $targetElem = $datesGrid.find('.cal-day[data-date="'+targetDate+'"]');
            if ($targetElem.length) { $targetElem.addClass('active'); showDetails(targetDate); }
        }

        function showDetails(dateStr) {
            $detailsContent.empty().show();
            var dayEvents = scheduleData[dateStr];
            if (!dayEvents) return;

            var stages = {};
            dayEvents.forEach(function(row) {
                var sName = row.stage || "Matches";
                if (!stages[sName]) stages[sName] = [];
                stages[sName].push(row);
            });

            for (var stageName in stages) {
                var stageRows = stages[stageName];
                
                // MULTI-STREAM LOGIC
                var streamData = stageRows[0].stream || "";
                var streams = {};
                try {
                    if (streamData.startsWith("{")) {
                        streams = JSON.parse(streamData);
                    } else if (streamData) {
                        streams["Watch"] = streamData; // Fallback for old data
                    }
                } catch(e) {}

                var streamBtns = "";
                for (var label in streams) {
                    var url = streams[label];
                    if (!url.match(/^https?:\/\//)) url = "https://" + url; 
                    
                    // Auto-Detect Icon (Twitch vs YouTube)
                    var icon = '<i class="fa-brands fa-youtube"></i>';
                    if (url.indexOf("twitch.tv") !== -1) {
                        icon = '<i class="fa-brands fa-twitch"></i>';
                    }
                    
                    streamBtns += '<a href="' + url + '" target="_blank" class="cal-stream-btn">' + icon + ' ' + label + '</a>';
                }
                
                var streamHtml = streamBtns ? '<div class="cal-stream-group">' + streamBtns + '</div>' : '';

                $detailsContent.append('<div class="cal-stage-header-wrap"><div class="cal-stage-header">' + stageName + '</div>' + streamHtml + '</div>');
                
                stageRows.forEach(function(row) {
                    row.data.forEach(function(match) {
                        var localTime = formatLocalTime(match.time);
                        
                        var html = '<div class="cal-match-row"><div class="cal-m-time">' + localTime + '</div>';

                        if (row.match_type === "BR") {
                            var map = match.map || "TBD";
                            var grp = match.group ? '<span class="cal-m-group">' + match.group + '</span>' : '';
                            html += '<div class="cal-m-info"><span class="cal-m-map">' + map + '</span>' + grp + '</div>';
                        } else {
                            var t1 = match.t1 || "TBD", t2 = match.t2 || "TBD";
                            var grp = match.group ? '<span class="cal-m-group">' + match.group + '</span>' : '';
                            html += '<div class="cal-m-info"><span class="cal-m-teams">' + t1 + ' vs ' + t2 + '</span>' + grp + '</div>';
                        }
                        html += '</div>';
                        $detailsContent.append(html);
                    });
                });
            }
        }

        $container.find('.cal-prev').on('click', function() {
            currentMonth--; if (currentMonth < 0) { currentMonth = 11; currentYear--; }
            renderCalendar();
        });
        $container.find('.cal-next').on('click', function() {
            currentMonth++; if (currentMonth > 11) { currentMonth = 0; currentYear++; }
            renderCalendar();
        });

        renderCalendar();
    });
});


/* ── COMMON.JS: dropdown toggle ── */
$(document).on('click', '.espa-dropdown-trigger', function(e) {
    e.stopPropagation();
    var $t = $(this);
    var $menu = $t.siblings('.espa-dropdown-menu');
    $t.toggleClass('open');
    $menu.toggleClass('open');
});
$(document).on('click', function() {
    $('.espa-dropdown-trigger').removeClass('open');
    $('.espa-dropdown-menu').removeClass('open');
});

/* ==============================================================
   BRACKET SYSTEM v2.0 JS — Add to MediaWiki:Common.js
   ============================================================== */

$(function () {

    /* ── Open modal on match card click ─────────────────────── */
    $(document).on('click', '.bk-match-clickable', function (e) {
        e.stopPropagation();

        var $m      = $(this);
        var team1   = $m.attr('data-team1')   || 'TBD';
        var team2   = $m.attr('data-team2')   || 'TBD';
        var score1  = $m.attr('data-score1')  || '';
        var score2  = $m.attr('data-score2')  || '';
        var bo      = $m.attr('data-bo')      || '';
        var date    = $m.attr('data-date')    || '';
        var casters = $m.attr('data-casters') || '';
        var vod     = $m.attr('data-vod')     || '';
        var notes   = $m.attr('data-notes')   || '';

        var $overlay = $m.closest('.bk-root').find('.bk-modal-overlay');
        if (!$overlay.length) { return; }

        $overlay.find('.bk-modal-t1').text(team1);
        $overlay.find('.bk-modal-t2').text(team2);

        var hasScore = (score1 !== '' || score2 !== '');
        $overlay.find('.bk-modal-s1').text(hasScore ? (score1 || '0') : '\u2014');
        $overlay.find('.bk-modal-s2').text(hasScore ? (score2 || '0') : '\u2014');
        $overlay.find('.bk-modal-dash').toggle(hasScore);

        /* Best-of */
        var $boRow = $overlay.find('.bk-modal-bo').empty();
        if (bo) {
            $boRow.append($('<b>').text('Format')).append(' Best of ' + bo);
        }

        /* Date — local timezone */
        var $dateRow = $overlay.find('.bk-modal-date').empty();
        if (date) {
            var dateText = date;
            try {
                var clean = date.indexOf('T') !== -1 ? date : date.replace(' ', 'T');
                var d = new Date(clean);
                if (!isNaN(d.getTime())) {
                    dateText = new Intl.DateTimeFormat('en-IN', {
                        year: 'numeric', month: 'short', day: 'numeric',
                        hour: 'numeric', minute: '2-digit',
                        timeZoneName: 'short'
                    }).format(d);
                }
            } catch (ex) { /* keep raw string */ }
            $dateRow.append($('<b>').text('Date')).append(' ' + dateText);
        }

        /* Casters */
        var $casterRow = $overlay.find('.bk-modal-casters').empty();
        if (casters) {
            $casterRow.append($('<b>').text('Casters')).append(' ' + casters);
        }

        /* Notes */
        var $notesRow = $overlay.find('.bk-modal-notes').empty();
        if (notes) {
            $notesRow.append($('<b>').text('Notes')).append(' ' + notes);
        }

        /* VOD */
        var $vodRow = $overlay.find('.bk-modal-vod').empty();
        if (vod) {
            var $link = $('<a>').attr('href', vod).attr('target', '_blank')
                .attr('rel', 'noopener noreferrer').text('Watch VOD');
            $vodRow.append($('<b>').text('VOD')).append(' ').append($link);
        }

        /* Score win/lose highlight */
        var win = $m.attr('data-winner') || '';
        $overlay.find('.bk-modal-s1').removeClass('bk-modal-win bk-modal-lose');
        $overlay.find('.bk-modal-s2').removeClass('bk-modal-win bk-modal-lose');
        if (win === '1' || win === team1) {
            $overlay.find('.bk-modal-s1').addClass('bk-modal-win');
            $overlay.find('.bk-modal-s2').addClass('bk-modal-lose');
        } else if (win === '2' || win === team2) {
            $overlay.find('.bk-modal-s2').addClass('bk-modal-win');
            $overlay.find('.bk-modal-s1').addClass('bk-modal-lose');
        }

        $overlay.fadeIn(150);
    });

    /* ── Close: X button ────────────────────────────────────── */
    $(document).on('click', '.bk-modal-close', function (e) {
        e.stopPropagation();
        $('.bk-modal-overlay').fadeOut(150);
    });

    /* ── Close: click outside modal box ─────────────────────── */
    $(document).on('click', '.bk-modal-overlay', function (e) {
        if ($(e.target).hasClass('bk-modal-overlay')) {
            $('.bk-modal-overlay').fadeOut(150);
        }
    });

    /* ── Close: Escape key ───────────────────────────────────── */
    $(document).on('keydown', function (e) {
        if (e.key === 'Escape' || e.keyCode === 27) {
            $('.bk-modal-overlay').fadeOut(150);
        }
    });

});


/* ================================================================
   BRACKET CONNECTOR LINES — SVG overlay drawn after layout
   Measures actual card positions so lines always hit card centres
   ================================================================ */

$(function () {

    function drawBracketConnectors() {

        /* ── GSL connectors ──────────────────────────────────── */
        $('.bk-gsl').each(function () {
            var $root    = $(this);
            var rootOff  = $root.offset();
            var rootW    = $root.outerWidth();
            var rootH    = $root.outerHeight();

            /* Remove old SVG if redrawing */
            $root.find('.bk-connector-svg').remove();

            var svgNS = 'http://www.w3.org/2000/svg';
            var svg   = document.createElementNS(svgNS, 'svg');
            svg.setAttribute('class', 'bk-connector-svg');
            svg.setAttribute('width',  rootW);
            svg.setAttribute('height', rootH);
            svg.style.position = 'absolute';
            svg.style.top  = '0';
            svg.style.left = '0';

            function midY($el) {
                if (!$el.length) return 0;
                var off = $el.offset();
                return (off.top - rootOff.top) + $el.outerHeight() / 2;
            }
            function midX($el, side) {
                if (!$el.length) return 0;
                var off = $el.offset();
                if (side === 'right') return (off.left - rootOff.left) + $el.outerWidth();
                return off.left - rootOff.left;
            }

            function line(x1, y1, x2, y2) {
                var l = document.createElementNS(svgNS, 'line');
                l.setAttribute('x1', Math.round(x1));
                l.setAttribute('y1', Math.round(y1));
                l.setAttribute('x2', Math.round(x2));
                l.setAttribute('y2', Math.round(y2));
                svg.appendChild(l);
            }

            var $col1 = $root.find('.bk-gsl-col1');
            var $col2 = $root.find('.bk-gsl-col2');
            var $col3 = $root.find('.bk-gsl-col3');

            var $q1   = $col1.find('.bk-gsl-top .bk-match');
            var $elim = $col1.find('.bk-gsl-bot .bk-match');
            var $q2   = $col2.find('.bk-gsl-mid .bk-match');
            var $fin  = $col3.find('.bk-gsl-final .bk-match');

            if ($q1.length && $q2.length) {
                var q1Right  = midX($q1,   'right');
                var q1Mid    = midY($q1);
                var elimRight= midX($elim, 'right');
                var elimMid  = midY($elim);
                var q2Left   = midX($q2,   'left');
                var q2Mid    = midY($q2);
                var midJoinX = q2Left - 10; /* vertical join point */

                /* Q1 horizontal arm → join */
                line(q1Right,   q1Mid,   midJoinX, q1Mid);
                /* Elim horizontal arm → join */
                line(elimRight, elimMid, midJoinX, elimMid);
                /* Vertical join between Q1 and Elim arms */
                line(midJoinX, q1Mid, midJoinX, elimMid);
                /* Horizontal from join midpoint → Q2 left */
                var joinMidY = (q1Mid + elimMid) / 2;
                line(midJoinX, joinMidY, q2Left, joinMidY);
            }

            if ($q2.length && $fin.length) {
                var q2Right = midX($q2,  'right');
                var q2MidY  = midY($q2);
                var finLeft = midX($fin, 'left');
                var finMidY = midY($fin);
                var midX2   = q2Right + (finLeft - q2Right) / 2;

                /* Q2 → midpoint horizontal */
                line(q2Right, q2MidY, midX2, q2MidY);
                /* Vertical drop/rise to Final midY */
                line(midX2, q2MidY, midX2, finMidY);
                /* midpoint → Final left */
                line(midX2, finMidY, finLeft, finMidY);
            }

            $root.prepend(svg);
        });

        /* ── Single Elim connectors ──────────────────────────── */
        $('.bk-single-elim').each(function () {
            var $root   = $(this);
            var rootOff = $root.offset();
            var rootW   = $root.outerWidth();
            var rootH   = $root.outerHeight();

            $root.find('.bk-connector-svg').remove();

            var svgNS = 'http://www.w3.org/2000/svg';
            var svg   = document.createElementNS(svgNS, 'svg');
            svg.setAttribute('class', 'bk-connector-svg');
            svg.setAttribute('width',  rootW);
            svg.setAttribute('height', rootH);
            svg.style.position = 'absolute';
            svg.style.top  = '0';
            svg.style.left = '0';

            $root.find('.has-connector .bk-match').each(function () {
                var $card = $(this);
                var off   = $card.offset();
                var x1    = (off.left - rootOff.left) + $card.outerWidth();
                var y1    = (off.top  - rootOff.top)  + $card.outerHeight() / 2;
                var x2    = x1 + 44;
                var l     = document.createElementNS(svgNS, 'line');
                l.setAttribute('x1', Math.round(x1));
                l.setAttribute('y1', Math.round(y1));
                l.setAttribute('x2', Math.round(x2));
                l.setAttribute('y2', Math.round(y2 || y1));
                svg.appendChild(l);
            });

            $root.prepend(svg);
        });
    }

    /* Draw on load and on window resize */
    setTimeout(drawBracketConnectors, 200);
    $(window).on('resize', function () {
        clearTimeout(window._bkResizeTimer);
        window._bkResizeTimer = setTimeout(drawBracketConnectors, 150);
    });
});