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 265: Line 265:
});
});


/* ==========================================================
  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 */
/* Active Tier Filter Highlight */

Latest revision as of 02:24, 14 June 2026

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

/* WAF-Safe Forum Link Injection (Targeted to Citizen DOM) */
(function() {
    function injectForumButton() {
        // Target the drawer (menu) container directly from your HTML
        var drawerContainer = document.querySelector('.citizen-drawer');
        
        if (!drawerContainer) return false; 
        if (document.getElementById('custom-forum-container')) return true; 
        
        // 1. Create a container that mimics Citizen's native header items
        var forumDiv = document.createElement('div');
        forumDiv.id = 'custom-forum-container';
        forumDiv.className = 'citizen-header__item';
        forumDiv.style.display = 'flex';
        forumDiv.style.alignItems = 'center';
        forumDiv.style.justifyContent = 'center';
        
        // 2. Create the interactive link
        var forumBtn = document.createElement('a');
        forumBtn.href = 'https://forum.esportsamaze.in';
        forumBtn.title = 'eSportsAmaze Forums';
        forumBtn.target = '_blank'; 
        forumBtn.rel = 'noopener noreferrer';
        forumBtn.style.display = 'flex';
        forumBtn.style.alignItems = 'center';
        forumBtn.style.justifyContent = 'center';
        forumBtn.style.width = '44px';
        forumBtn.style.height = '44px';
        forumBtn.style.color = 'var(--color-base, #ffffff)';
        forumBtn.style.opacity = '0.7';
        forumBtn.style.cursor = 'pointer';
        forumBtn.style.transition = 'opacity 0.2s ease-in-out';
        
        // Hover effects
        forumBtn.onmouseover = function() { this.style.opacity = '1'; };
        forumBtn.onmouseout = function() { this.style.opacity = '0.7'; };

// 3. Create the icon wrapper (Fixed to prevent the dark rectangle)
        var iconSpan = document.createElement('span');
        iconSpan.style.display = 'flex';
        iconSpan.style.alignItems = 'center';
        iconSpan.style.justifyContent = 'center';

        // 4. Build the SVG programmatically (Bypasses Hostinger WAF)
        var svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
        svg.setAttribute('width', '24');
        svg.setAttribute('height', '24');
        svg.setAttribute('viewBox', '0 0 24 24');
        svg.setAttribute('fill', 'none');
        svg.setAttribute('stroke', 'currentColor');
        svg.setAttribute('stroke-width', '2');
        svg.setAttribute('stroke-linecap', 'round');
        svg.setAttribute('stroke-linejoin', 'round');

        var path = document.createElementNS('http://www.w3.org/2000/svg', 'path');
        path.setAttribute('d', 'M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z');
        
        // 5. Assemble everything
        svg.appendChild(path);
        iconSpan.appendChild(svg);
        forumBtn.appendChild(iconSpan);
        forumDiv.appendChild(forumBtn);
        
        // 6. Inject right after the menu drawer toggle
        drawerContainer.insertAdjacentElement('afterend', forumDiv);
        
        return true;
    }

    // Run immediately and poll if ResourceLoader delays DOM execution
    if (!injectForumButton()) {
        var attempts = 0;
        var timer = setInterval(function() {
            attempts++;
            if (injectForumButton() || attempts > 50) {
                clearInterval(timer);
            }
        }, 100);
    }
})();

/* WAF-Safe Dynamic Forum Icon Injection (Page Header) */
mw.hook('wikipage.content').add(function($content) {
    // 1. Check if the "Discuss" template is actively used on this specific page
    var dataDiv = document.getElementById('ea-forum-discuss-data');
    if (!dataDiv) return; // Exit quietly if the template isn't on this page

    var forumUrl = dataDiv.getAttribute('data-forum-link');
    if (!forumUrl || document.getElementById('ea-header-forum-btn')) return; 

    // 2. Find the target area (Citizen's Top Right Actions menu)
    var targetContainer = document.querySelector('.citizen-page-actions') || document.querySelector('.page-actions-menu') || document.querySelector('#p-views ul');
    if (!targetContainer) return;

    // 3. Create the button securely (Bypassing Hostinger WAF)
    var forumBtn = document.createElement('a');
    forumBtn.id = 'ea-header-forum-btn';
    forumBtn.href = forumUrl;
    forumBtn.target = '_blank';
    forumBtn.rel = 'noopener noreferrer';
    forumBtn.title = 'Discuss this on the Forums';
    
    // 4. Style it to match Citizen's native action buttons
    forumBtn.style.display = 'inline-flex';
    forumBtn.style.alignItems = 'center';
    forumBtn.style.gap = '6px';
    forumBtn.style.color = 'var(--color-base, #ffffff)';
    forumBtn.style.textDecoration = 'none';
    forumBtn.style.fontWeight = '600';
    forumBtn.style.fontSize = '0.875rem';
    forumBtn.style.padding = '6px 8px';
    forumBtn.style.borderRadius = '4px';
    forumBtn.style.marginLeft = '4px';
    forumBtn.style.transition = 'background-color 0.2s';

    // Hover effects
    forumBtn.onmouseover = function() { this.style.backgroundColor = 'var(--color-surface-2, rgba(128,128,128,0.15))'; };
    forumBtn.onmouseout = function() { this.style.backgroundColor = 'transparent'; };

    // 5. Create a distinct SVG icon (Rounded chat bubble to look different from standard "Comments")
    var svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
    svg.setAttribute('width', '18');
    svg.setAttribute('height', '18');
    svg.setAttribute('viewBox', '0 0 24 24');
    svg.setAttribute('fill', 'none');
    svg.setAttribute('stroke', 'currentColor');
    svg.setAttribute('stroke-width', '2');
    svg.setAttribute('stroke-linecap', 'round');
    svg.setAttribute('stroke-linejoin', 'round');
    
    var path = document.createElementNS('http://www.w3.org/2000/svg', 'path');
    path.setAttribute('d', 'M21 11.5a8.38 8.38 0 0 1-.9 3.8 8.5 8.5 0 0 1-7.6 4.7 8.38 8.38 0 0 1-3.8-.9L3 21l1.9-5.7a8.38 8.38 0 0 1-.9-3.8 8.5 8.5 0 0 1 4.7-7.6 8.38 8.38 0 0 1 3.8-.9h.5a8.48 8.48 0 0 1 8 8v.5z');

    // 6. Text label
    var textSpan = document.createElement('span');
    textSpan.textContent = 'Forum'; 

    // Assemble and inject next to Share/Comments
    svg.appendChild(path);
    forumBtn.appendChild(svg);
    forumBtn.appendChild(textSpan);
    targetContainer.appendChild(forumBtn);
});


/* ==========================================================
   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);
});


/* 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() {

  // ── ADMIN BYPASS ──────────────────────────────────────────
  var userGroups = mw.config.get('wgUserGroups') || [];
  var adminGroups = ['sysop', 'bureaucrat'];
  var isAdmin = adminGroups.some(function(g) { return userGroups.indexOf(g) !== -1; });
  if (isAdmin) return;
  // ──────────────────────────────────────────────────────────

// 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 v3.0: SVG ROUTER + POPUPS
   ================================================================ */
$(function () {
    const svgNS = 'http://www.w3.org/2000/svg';

    // 1. SVG LINE ROUTER (Now supports multiple outgoing lines)
    function drawBracketLines() {
        $('.bk-root').each(function () {
            let $root = $(this);
            let $wrapper = $root.find('.bk-wrapper');
            if (!$wrapper.length) return;

            $wrapper.find('.bk-svg-layer').remove();
            let wrapperRect = $wrapper[0].getBoundingClientRect();
            
            let svg = document.createElementNS(svgNS, 'svg');
            svg.setAttribute('class', 'bk-svg-layer');
            svg.style.width = wrapperRect.width + 'px';
            svg.style.height = wrapperRect.height + 'px';
            $wrapper.prepend(svg);

            $wrapper.find('.bk-match').each(function () {
                let $source = $(this);
                let targets = [];
                
                // 1. Check for standard/winner target
                let tWin = $source.attr('data-target-win') || $source.attr('data-target');
                if (tWin) targets.push({ id: tWin, isDrop: $source.attr('data-drop') === "true" });
                
                // 2. Check for loser target (automatically styled as a "drop" line)
                let tLose = $source.attr('data-target-lose');
                if (tLose) targets.push({ id: tLose, isDrop: true });

                targets.forEach(t => {
                    let $target = $wrapper.find('#' + t.id);
                    if ($target.length) {
                        let $sWrap = $source.find('.bk-teams-wrap');
                        let $tWrap = $target.find('.bk-teams-wrap');
                        
                        let sRect = $sWrap.length ? $sWrap[0].getBoundingClientRect() : $source[0].getBoundingClientRect();
                        let tRect = $tWrap.length ? $tWrap[0].getBoundingClientRect() : $target[0].getBoundingClientRect();

                        let startX = (sRect.right - wrapperRect.left);
                        let startY = (sRect.top - wrapperRect.top) + (sRect.height / 2);
                        let endX = (tRect.left - wrapperRect.left);
                        let endY = (tRect.top - wrapperRect.top) + (tRect.height / 2);

                        let midX = startX + (endX - startX) / 2;

                        let path = document.createElementNS(svgNS, 'path');
                        let d = `M ${startX},${startY} L ${midX},${startY} L ${midX},${endY} L ${endX},${endY}`;
                        
                        path.setAttribute('d', d);
                        path.setAttribute('class', t.isDrop ? 'bk-line bk-line-drop' : 'bk-line');
                        svg.appendChild(path);
                    }
                });
            });
        });
    }

    setTimeout(drawBracketLines, 300);
    $(window).on('resize', function () {
        clearTimeout(window._bkResizeTimer);
        window._bkResizeTimer = setTimeout(drawBracketLines, 100);
    });

    // 2. MODAL POPUPS (Triggered by clicking the ENTIRE Top Bar)
    $(document).on('click', '.bk-match-top', function (e) {
        e.stopPropagation();

        var $trigger = $(this);
        
        // Grabs the ID for your future "Match Data Page" logic!
        var matchId = $trigger.attr('data-matchid') || ''; 
        
        var team1   = $trigger.attr('data-team1')   || 'TBD';
        var team2   = $trigger.attr('data-team2')   || 'TBD';
        var score1  = $trigger.attr('data-score1')  || '';
        var score2  = $trigger.attr('data-score2')  || '';
        var bo      = $trigger.attr('data-bo')      || '';
        var date    = $trigger.attr('data-date')    || '';
        var casters = $trigger.attr('data-casters') || '';
        var vod     = $trigger.attr('data-vod')     || '';
        var notes   = $trigger.attr('data-notes')   || '';

        var $overlay = $trigger.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);

        $overlay.find('.bk-modal-bo').empty().append(bo ? $('<b>').text('Format').add($('<span>').text(' Best of ' + bo)) : '');
        $overlay.find('.bk-modal-date').empty().append(date ? $('<b>').text('Date').add($('<span>').text(' ' + date)) : '');
        $overlay.find('.bk-modal-casters').empty().append(casters ? $('<b>').text('Casters').add($('<span>').text(' ' + casters)) : '');
        $overlay.find('.bk-modal-notes').empty().append(notes ? $('<b>').text('Notes').add($('<span>').text(' ' + notes)) : '');
        
        $overlay.find('.bk-modal-vod').empty();
        if (vod) {
            $overlay.find('.bk-modal-vod').append($('<b>').text('VOD')).append(' ').append($('<a>').attr('href', vod).attr('target', '_blank').text('Watch VOD'));
        }

        $overlay.css('display', 'flex').hide().fadeIn(150);
    });

    $(document).on('click', '.bk-modal-close, .bk-modal-overlay', function (e) {
        if ($(e.target).hasClass('bk-modal-overlay') || $(e.target).hasClass('bk-modal-close')) {
            $('.bk-modal-overlay').fadeOut(150);
        }
    });
    $(document).on('keydown', function (e) {
        if (e.key === 'Escape' || e.keyCode === 27) $('.bk-modal-overlay').fadeOut(150);
    });
});