MediaWiki:TeamBingo.js: Difference between revisions

From Roat Pkz
Jump to navigation Jump to search
No edit summary
No edit summary
Line 1: Line 1:
// --- Team Bingo Board with Smart Live Updates ---
// --- Team Bingo Board with Captains and Smart Live Updates ---
mw.hook('wikipage.content').add(function () {
mw.hook('wikipage.content').add(function () {


const currentUser = mw.config.get('wgUserName') || "";
    const currentUser = mw.config.get('wgUserName'); // logged-in user
const containers = document.querySelectorAll(".teamBingoContainer");
    const containers = document.querySelectorAll(".teamBingoContainer");
if (!containers.length) return;
    if (!containers.length) return;


const infoBox = document.getElementById("teamBingoInfoBox");
    // Shared info box
    const infoBox = document.getElementById("teamBingoInfoBox");


const defaultInfoHTML = `
    // Set default bingo info immediately on page load
<div style="text-align:center;font-size:18px;font-weight:bold;margin-bottom:6px;">
    infoBox.innerHTML = `
Team Bingo Challenge
<div style="text-align: center; font-weight: bold; font-size: 16px; margin-bottom: 8px;">
  Team Bingo Challenge
</div>
</div>
Welcome to the <strong>Roat Pkz Team Bingo #3</strong> event. Each team has its own bingo board — your goal is to collect the drops or items listed on your team’s board to score points. Each completed tile = 1 point.<br><br>


This is a <b>team-based bingo event</b>. Work together to complete tiles by obtaining drops from PvM or skilling activities.
<strong>Rules:</strong><br>
- Only <strong>team captains</strong> can mark tiles for their team.<br>
- Your board updates <strong>in real time</strong> for all team members.<br>
- Screenshots of drops/items are required for verification.<br>
- Chests, crates, and boxes do <em>not</em> count.<br><br>


<ul style="margin-top:6px;">
<strong>Event ends:</strong> June 28th, 11:59 PM GMT<br><br>
<li>Each qualifying drop = <b>1 point</b></li>
<li>Screenshots are required for submissions</li>
<li>Chests, crates, and boxes do <b>not</b> count</li>
<li>The board updates <b>live automatically</b></li>
</ul>


<b>Team captains</b> can mark tiles as completed.
<strong>Rewards:</strong><br>
- 500 CREDITS (25M+) — 1st place<br>
- 300 CREDITS (15M+) — 2nd place<br>
- 200 CREDITS (10M+) — 3rd place<br><br>
`;
`;


infoBox.innerHTML = defaultInfoHTML;
    const boardState = {}; // central source of truth for all tiles
    let lastRevisionId = null; // for smart polling


const boardState = {};
    // Fetch JSON from Module page
let lastRevisionId = null;
    function fetchBoardData(callback) {
let isSaving = false;
        $.getJSON(mw.util.wikiScript('api'), {
            action: 'query',
            titles: 'Module:TeamBingo/data.json',
            prop: 'revisions',
            rvprop: 'content|ids',
            format: 'json',
            formatversion: 2
        }).done(function(data){
            const page = data.query.pages[0];
            if (!page.revisions) return;


// --------------------------------------------------
            const revId = page.revisions[0].revid;
// Fetch JSON board data
            const content = page.revisions[0].content;
// --------------------------------------------------


function fetchBoardData(callback){
            if (lastRevisionId === null) lastRevisionId = revId;


$.getJSON(mw.util.wikiScript('api'),{
            // Only update if revision changed
action:"query",
            if (revId !== lastRevisionId) {
titles:"Module:TeamBingo/data.json",
                lastRevisionId = revId;
prop:"revisions",
                try {
rvprop:"content|ids",
                    const json = JSON.parse(content);
rvslots:"main",
                    Object.assign(boardState, json);
formatversion:2,
                    if (callback) callback(boardState);
format:"json"
                } catch(e) {
}).done(function(data){
                    console.error("Failed to parse JSON from Module:TeamBingo/data.json", e);
                }
            } else if (callback) {
                callback(boardState); // still call for initial load
            }
        });
    }


const page = data.query.pages[0];
    // Render the board (unchanged)
if(!page.revisions) return;
    function renderBoard(container, teamKey) {


const revision = page.revisions[0];
        container.innerHTML = "";
const content = revision.slots.main.content;
        const captain = container.getAttribute("data-captain");
        const itemsAttr = container.getAttribute("data-items");
        if (!itemsAttr) return;
       
        // --- ADD TEAM NAME ---
        const teamNameDiv = document.createElement("div");
        teamNameDiv.textContent = container.getAttribute("data-team") === "teamA" ? "Team A" : "Team B";
        teamNameDiv.style.fontWeight = "bold";
        teamNameDiv.style.fontSize = "18px";
        teamNameDiv.style.color = "#fff";
        teamNameDiv.style.textAlign = "center";
        teamNameDiv.style.marginBottom = "10px";
        container.appendChild(teamNameDiv);
        // --- END TEAM NAME ---


lastRevisionId = revision.revid;
        const items = itemsAttr.split("|").filter(i => i.trim() !== "");
        if (!items.length) return;


try{
        const parsedItems = items.map(entry => {
const json = JSON.parse(content);
            const parts = entry.split("::");
Object.assign(boardState,json);
            return { name: parts[0].trim(), tooltip: parts[1] ? parts[1].trim() : parts[0].trim() };
}catch(e){
        });
console.error("JSON parse error",e);
}


if(callback) callback(boardState);
        const table = document.createElement("table");
        table.style.tableLayout = "fixed";
        table.style.border = "2px solid #596e96";
        table.style.borderCollapse = "collapse";
        table.style.borderRadius = "8px";
        table.style.width = "100%";
        container.appendChild(table);


});
        const rows = Math.ceil(Math.sqrt(parsedItems.length));
        const cols = Math.ceil(parsedItems.length / rows);


}
        const allTemplates = parsedItems.map(item => `{{plinkp|${item.name}}}`).join("\n");
        $.getJSON("/api.php", { action: "parse", text: allTemplates, format: "json" }).done(function(data) {
            if (!data.parse || !data.parse.text) return;
            const tempDiv = document.createElement("div");
            tempDiv.innerHTML = data.parse.text["*"];
            const imgs = tempDiv.querySelectorAll("img");


// --------------------------------------------------
            for (let r = 0; r < rows; r++) {
// Render Board
                const row = table.insertRow();
// --------------------------------------------------
                for (let c = 0; c < cols; c++) {
                    const index = r * cols + c;
                    if (index >= parsedItems.length) break;


function renderBoard(container,teamKey){
                    const item = parsedItems[index];
                    const cell = row.insertCell();
                    const id = `${container.id}_cell_${index}`;
                    cell.id = id;


if(!boardState[teamKey]){
                    cell.style.width = `${100 / cols}%`;
boardState[teamKey] = {};
                    cell.style.padding = "10px";
}
                    cell.style.border = "1px solid #596e96";
                    cell.style.textAlign = "center";
                    cell.style.background = boardState[teamKey][`tile_${index}`] ? "rgba(76,175,80,0.5)" : "#313e59";
                    cell.style.color = "#fff";
                    cell.style.cursor = "pointer";
                    cell.style.transition = "all 0.2s ease";
                    cell.style.position = "relative";
                    cell.style.userSelect = "none";


const rawItems = container.dataset.items.trim();
                    const cellContainer = document.createElement("div");
                    cellContainer.style.position = "relative";
                    cellContainer.style.width = "100%";
                    cellContainer.style.height = "100%";


const items = rawItems.split("|").map(entry=>{
                    // Image
const parts = entry.split("::");
                    if (imgs[index]) {
return {
                        const img = document.createElement("img");
name: parts[0].trim(),
                        img.src = imgs[index].src;
description: parts[1] ? parts[1].trim() : ""
                        img.alt = item.name;
};
                        img.style.width = "40px";
});
                        img.style.height = "auto";
                        img.style.display = "block";
                        img.style.margin = "0 auto";
                        cellContainer.appendChild(img);
                    }


const captains = container.dataset.captain
                    // Name
.split(",")
                    const nameDiv = document.createElement("div");
.map(c=>c.trim().toLowerCase());
                    nameDiv.textContent = item.name;
                    nameDiv.style.marginTop = "5px";
                    nameDiv.style.pointerEvents = "none";
                    cellContainer.appendChild(nameDiv);


const table = document.createElement("table");
                    // Checkmark
table.className = "teamBingoBoard";
                    const checkmark = document.createElement("div");
                    checkmark.textContent = "✔";
                    checkmark.className = "bingoCheckmark";
                    checkmark.style.position = "absolute";
                    checkmark.style.top = "2px";
                    checkmark.style.right = "2px";
                    checkmark.style.fontSize = "20px";
                    checkmark.style.color = "#4CAF50";
                    checkmark.style.display = boardState[teamKey][`tile_${index}`] ? "block" : "none";
                    cellContainer.appendChild(checkmark);


let row = null;
                    // Hover shows info but preserves green
                    cell.addEventListener("mouseenter", function() {
                        if (!boardState[teamKey][`tile_${index}`]) cell.style.background = "#3b4a6b";


items.forEach((item,index)=>{
                        infoBox.innerHTML = "";
                        const header = document.createElement("div");
                        header.style.fontWeight = "bold";
                        header.style.marginBottom = "5px";
                        header.textContent = item.name;
                        infoBox.appendChild(header);


if(index % 5 === 0){
                        if (imgs[index]) {
row = document.createElement("tr");
                            const hoverImg = document.createElement("img");
table.appendChild(row);
                            hoverImg.src = imgs[index].src;
}
                            hoverImg.style.width = "40px";
                            hoverImg.style.height = "auto";
                            hoverImg.style.display = "block";
                            hoverImg.style.marginBottom = "5px";
                            infoBox.appendChild(hoverImg);
                        }


const cell = document.createElement("td");
                        item.tooltip.split("%%").forEach(line => {
cell.className = "bingoTile";
                            const div = document.createElement("div");
                            div.innerHTML = line.trim();
                            infoBox.appendChild(div);
                        });
                    });


cell.innerHTML = `
                    cell.addEventListener("mouseleave", function() {
<div class="bingoText">${item.name}</div>
                        cell.style.background = boardState[teamKey][`tile_${index}`] ? "rgba(76,175,80,0.5)" : "#313e59";
<div class="bingoCheckmark"></div>
                        infoBox.innerHTML = `
`;
<div style="text-align: center; font-weight: bold; font-size: 16px; margin-bottom: 8px;">
 
  Team Bingo Challenge
const done = boardState[teamKey][`tile_${index}`];
</div>
Welcome to the <strong>Roat Pkz Team Bingo #3</strong> event. Each team has its own bingo board — your goal is to collect the drops or items listed on your team’s board to score points. Each completed tile = 1 point.<br><br>


if(done){
<strong>Rules:</strong><br>
cell.style.background = "rgba(76,175,80,0.5)";
- Only <strong>team captains</strong> can mark tiles for their team.<br>
cell.querySelector(".bingoCheckmark").style.display="block";
- Your board updates <strong>in real time</strong> for all team members.<br>
}
- Screenshots of drops/items are required for verification.<br>
- Chests, crates, and boxes do <em>not</em> count.<br><br>


cell.addEventListener("mouseenter",()=>{
<strong>Event ends:</strong> June 28th, 11:59 PM GMT<br><br>


infoBox.innerHTML = `
<strong>Rewards:</strong><br>
<b>${item.name}</b><br>
- 500 CREDITS (25M+) — 1st place<br>
${item.description || ""}
- 300 CREDITS (15M+) — 2nd place<br>
- 200 CREDITS (10M+) — 3rd place<br><br>
`;
`;
                    });


});
                    // Click to toggle (captain only)
 
                    cell.addEventListener("click", function() {
cell.addEventListener("mouseleave",()=>{
                        const captainList = container.getAttribute("data-captain").split(",").map(u => u.trim());
infoBox.innerHTML = defaultInfoHTML;
                        if (!captainList.includes(currentUser)) return;
});
 
if(captains.includes(currentUser.toLowerCase())){
 
cell.style.cursor="pointer";
 
cell.addEventListener("click",()=>{
 
const current = boardState[teamKey][`tile_${index}`];
const newValue = !current;
 
boardState[teamKey][`tile_${index}`] = newValue;
 
updateTileVisual(cell,newValue);
 
saveTile(teamKey,index,newValue);
 
});
 
}
 
row.appendChild(cell);
 
});
 
container.innerHTML="";
container.appendChild(table);
 
}
 
// --------------------------------------------------
// Update Tile Visual
// --------------------------------------------------
 
function updateTileVisual(cell,done){
 
const checkmark = cell.querySelector(".bingoCheckmark");
 
if(done){
cell.style.background="rgba(76,175,80,0.5)";
checkmark.style.display="block";
}else{
cell.style.background="#313e59";
checkmark.style.display="none";
}
 
}
 
// --------------------------------------------------
// Save Tile to JSON Page
// --------------------------------------------------
 
function saveTile(teamKey,index,value){
 
if(isSaving) return;
isSaving = true;
 
fetchBoardData(function(data){
 
if(!data[teamKey]) data[teamKey] = {};
 
data[teamKey][`tile_${index}`] = value;
 
new mw.Api().postWithToken("csrf",{
action:"edit",
title:"Module:TeamBingo/data.json",
text:JSON.stringify(data,null,2),
summary:`Updated ${teamKey} tile ${index}`,
contentmodel:"json"
}).always(()=>{
isSaving = false;
});
 
});
 
}
 
// --------------------------------------------------
// Smart Polling (Revision Check)
// --------------------------------------------------
 
function checkForBoardUpdates(){
 
if(document.hidden || isSaving) return;
 
$.getJSON(mw.util.wikiScript('api'),{
action:"query",
titles:"Module:TeamBingo/data.json",
prop:"revisions",
rvprop:"ids",
format:"json",
formatversion:2
}).done(function(data){
 
const page = data.query.pages[0];
if(!page.revisions) return;
 
const revId = page.revisions[0].revid;
 
if(revId === lastRevisionId) return;
 
lastRevisionId = revId;
 
fetchBoardData(function(newState){
updateChangedTiles(newState);
});
 
});
 
}
 
// --------------------------------------------------
// Update Only Changed Tiles
// --------------------------------------------------
 
function updateChangedTiles(newState){
 
containers.forEach(container=>{
 
const teamKey = container.dataset.team;
const cells = container.querySelectorAll("td");
 
cells.forEach((cell,index)=>{
 
const oldVal = boardState[teamKey]?.[`tile_${index}`];
const newVal = newState[teamKey]?.[`tile_${index}`];
 
if(oldVal !== newVal){
 
boardState[teamKey][`tile_${index}`] = newVal;
updateTileVisual(cell,newVal);
 
}
 
});
 
});
 
}


// --------------------------------------------------
                        const done = boardState[teamKey][`tile_${index}`];
// Initial Load
                        boardState[teamKey][`tile_${index}`] = !done;
// --------------------------------------------------
                        checkmark.style.display = !done ? "block" : "none";
                        cell.style.background = !done ? "rgba(76,175,80,0.5)" : "#313e59";


fetchBoardData(function(){
                        // Save to MediaWiki
                        $.post(mw.util.wikiScript('api'), {
                            action: 'edit',
                            title: 'Module:TeamBingo/data.json',
                            token: mw.user.tokens.get('csrfToken'),
                            format: 'json',
                            text: JSON.stringify(boardState, null, 4)
                        }).done(() => console.log("Board updated for everyone!"));
                    });


containers.forEach(container=>{
                    cell.appendChild(cellContainer);
                }
            }


const teamKey = container.dataset.team;
            // Progress
renderBoard(container,teamKey);
            const progressDiv = document.createElement("div");
            progressDiv.style.marginTop = "10px";
            progressDiv.style.color = "#fff";
            progressDiv.className = "bingoProgress";
            container.appendChild(progressDiv);


});
            function updateProgress() {
                let completed = 0;
                for (let i = 0; i < parsedItems.length; i++)
                    if (boardState[teamKey][`tile_${i}`]) completed++;
                progressDiv.textContent = `Completed ${completed} of ${parsedItems.length} items`;
            }
            updateProgress();
        });
    }


});
    // Initial render
    fetchBoardData(function(boardData){
        containers.forEach(container => {
            const teamKey = container.getAttribute("data-team");
            renderBoard(container, teamKey);
        });
    });


// --------------------------------------------------
    // --- Smart Polling every 5s ---
// Start Smart Polling
    setInterval(function() {
// --------------------------------------------------
        fetchBoardData(function(newState){
            containers.forEach(container => {
                const teamKey = container.getAttribute("data-team");
                const cells = container.querySelectorAll("td");
                cells.forEach((cell,index)=>{
                    const checkmark = cell.querySelector(".bingoCheckmark");
                    const done = newState[teamKey][`tile_${index}`];
                    const oldDone = boardState[teamKey][`tile_${index}`];


setInterval(checkForBoardUpdates,5000);
                    if(done !== oldDone){
                        boardState[teamKey][`tile_${index}`] = done;
                        if(checkmark){
                            checkmark.style.display = done ? "block" : "none";
                            cell.style.background = done ? "rgba(76,175,80,0.5)" : "#313e59";
                        }
                    }
                });
            });
        });
    }, 5000);


});
});

Revision as of 17:28, 7 March 2026

// --- Team Bingo Board with Captains and Smart Live Updates ---
mw.hook('wikipage.content').add(function () {

    const currentUser = mw.config.get('wgUserName'); // logged-in user
    const containers = document.querySelectorAll(".teamBingoContainer");
    if (!containers.length) return;

    // Shared info box
    const infoBox = document.getElementById("teamBingoInfoBox");

    // Set default bingo info immediately on page load
    infoBox.innerHTML = `
<div style="text-align: center; font-weight: bold; font-size: 16px; margin-bottom: 8px;">
  Team Bingo Challenge
</div>
Welcome to the <strong>Roat Pkz Team Bingo #3</strong> event. Each team has its own bingo board — your goal is to collect the drops or items listed on your team’s board to score points. Each completed tile = 1 point.<br><br>

<strong>Rules:</strong><br>
- Only <strong>team captains</strong> can mark tiles for their team.<br>
- Your board updates <strong>in real time</strong> for all team members.<br>
- Screenshots of drops/items are required for verification.<br>
- Chests, crates, and boxes do <em>not</em> count.<br><br>

<strong>Event ends:</strong> June 28th, 11:59 PM GMT<br><br>

<strong>Rewards:</strong><br>
- 500 CREDITS (25M+) — 1st place<br>
- 300 CREDITS (15M+) — 2nd place<br>
- 200 CREDITS (10M+) — 3rd place<br><br>
`;

    const boardState = {}; // central source of truth for all tiles
    let lastRevisionId = null; // for smart polling

    // Fetch JSON from Module page
    function fetchBoardData(callback) {
        $.getJSON(mw.util.wikiScript('api'), {
            action: 'query',
            titles: 'Module:TeamBingo/data.json',
            prop: 'revisions',
            rvprop: 'content|ids',
            format: 'json',
            formatversion: 2
        }).done(function(data){
            const page = data.query.pages[0];
            if (!page.revisions) return;

            const revId = page.revisions[0].revid;
            const content = page.revisions[0].content;

            if (lastRevisionId === null) lastRevisionId = revId;

            // Only update if revision changed
            if (revId !== lastRevisionId) {
                lastRevisionId = revId;
                try {
                    const json = JSON.parse(content);
                    Object.assign(boardState, json);
                    if (callback) callback(boardState);
                } catch(e) {
                    console.error("Failed to parse JSON from Module:TeamBingo/data.json", e);
                }
            } else if (callback) {
                callback(boardState); // still call for initial load
            }
        });
    }

    // Render the board (unchanged)
    function renderBoard(container, teamKey) {

        container.innerHTML = "";
        const captain = container.getAttribute("data-captain");
        const itemsAttr = container.getAttribute("data-items");
        if (!itemsAttr) return;
        
        // --- ADD TEAM NAME ---
        const teamNameDiv = document.createElement("div");
        teamNameDiv.textContent = container.getAttribute("data-team") === "teamA" ? "Team A" : "Team B";
        teamNameDiv.style.fontWeight = "bold";
        teamNameDiv.style.fontSize = "18px";
        teamNameDiv.style.color = "#fff";
        teamNameDiv.style.textAlign = "center";
        teamNameDiv.style.marginBottom = "10px";
        container.appendChild(teamNameDiv);
        // --- END TEAM NAME ---

        const items = itemsAttr.split("|").filter(i => i.trim() !== "");
        if (!items.length) return;

        const parsedItems = items.map(entry => {
            const parts = entry.split("::");
            return { name: parts[0].trim(), tooltip: parts[1] ? parts[1].trim() : parts[0].trim() };
        });

        const table = document.createElement("table");
        table.style.tableLayout = "fixed";
        table.style.border = "2px solid #596e96";
        table.style.borderCollapse = "collapse";
        table.style.borderRadius = "8px";
        table.style.width = "100%";
        container.appendChild(table);

        const rows = Math.ceil(Math.sqrt(parsedItems.length));
        const cols = Math.ceil(parsedItems.length / rows);

        const allTemplates = parsedItems.map(item => `{{plinkp|${item.name}}}`).join("\n");
        $.getJSON("/api.php", { action: "parse", text: allTemplates, format: "json" }).done(function(data) {
            if (!data.parse || !data.parse.text) return;
            const tempDiv = document.createElement("div");
            tempDiv.innerHTML = data.parse.text["*"];
            const imgs = tempDiv.querySelectorAll("img");

            for (let r = 0; r < rows; r++) {
                const row = table.insertRow();
                for (let c = 0; c < cols; c++) {
                    const index = r * cols + c;
                    if (index >= parsedItems.length) break;

                    const item = parsedItems[index];
                    const cell = row.insertCell();
                    const id = `${container.id}_cell_${index}`;
                    cell.id = id;

                    cell.style.width = `${100 / cols}%`;
                    cell.style.padding = "10px";
                    cell.style.border = "1px solid #596e96";
                    cell.style.textAlign = "center";
                    cell.style.background = boardState[teamKey][`tile_${index}`] ? "rgba(76,175,80,0.5)" : "#313e59";
                    cell.style.color = "#fff";
                    cell.style.cursor = "pointer";
                    cell.style.transition = "all 0.2s ease";
                    cell.style.position = "relative";
                    cell.style.userSelect = "none";

                    const cellContainer = document.createElement("div");
                    cellContainer.style.position = "relative";
                    cellContainer.style.width = "100%";
                    cellContainer.style.height = "100%";

                    // Image
                    if (imgs[index]) {
                        const img = document.createElement("img");
                        img.src = imgs[index].src;
                        img.alt = item.name;
                        img.style.width = "40px";
                        img.style.height = "auto";
                        img.style.display = "block";
                        img.style.margin = "0 auto";
                        cellContainer.appendChild(img);
                    }

                    // Name
                    const nameDiv = document.createElement("div");
                    nameDiv.textContent = item.name;
                    nameDiv.style.marginTop = "5px";
                    nameDiv.style.pointerEvents = "none";
                    cellContainer.appendChild(nameDiv);

                    // Checkmark
                    const checkmark = document.createElement("div");
                    checkmark.textContent = "✔";
                    checkmark.className = "bingoCheckmark";
                    checkmark.style.position = "absolute";
                    checkmark.style.top = "2px";
                    checkmark.style.right = "2px";
                    checkmark.style.fontSize = "20px";
                    checkmark.style.color = "#4CAF50";
                    checkmark.style.display = boardState[teamKey][`tile_${index}`] ? "block" : "none";
                    cellContainer.appendChild(checkmark);

                    // Hover shows info but preserves green
                    cell.addEventListener("mouseenter", function() {
                        if (!boardState[teamKey][`tile_${index}`]) cell.style.background = "#3b4a6b";

                        infoBox.innerHTML = "";
                        const header = document.createElement("div");
                        header.style.fontWeight = "bold";
                        header.style.marginBottom = "5px";
                        header.textContent = item.name;
                        infoBox.appendChild(header);

                        if (imgs[index]) {
                            const hoverImg = document.createElement("img");
                            hoverImg.src = imgs[index].src;
                            hoverImg.style.width = "40px";
                            hoverImg.style.height = "auto";
                            hoverImg.style.display = "block";
                            hoverImg.style.marginBottom = "5px";
                            infoBox.appendChild(hoverImg);
                        }

                        item.tooltip.split("%%").forEach(line => {
                            const div = document.createElement("div");
                            div.innerHTML = line.trim();
                            infoBox.appendChild(div);
                        });
                    });

                    cell.addEventListener("mouseleave", function() {
                        cell.style.background = boardState[teamKey][`tile_${index}`] ? "rgba(76,175,80,0.5)" : "#313e59";
                        infoBox.innerHTML = `
<div style="text-align: center; font-weight: bold; font-size: 16px; margin-bottom: 8px;">
  Team Bingo Challenge
</div>
Welcome to the <strong>Roat Pkz Team Bingo #3</strong> event. Each team has its own bingo board — your goal is to collect the drops or items listed on your team’s board to score points. Each completed tile = 1 point.<br><br>

<strong>Rules:</strong><br>
- Only <strong>team captains</strong> can mark tiles for their team.<br>
- Your board updates <strong>in real time</strong> for all team members.<br>
- Screenshots of drops/items are required for verification.<br>
- Chests, crates, and boxes do <em>not</em> count.<br><br>

<strong>Event ends:</strong> June 28th, 11:59 PM GMT<br><br>

<strong>Rewards:</strong><br>
- 500 CREDITS (25M+) — 1st place<br>
- 300 CREDITS (15M+) — 2nd place<br>
- 200 CREDITS (10M+) — 3rd place<br><br>
`;
                    });

                    // Click to toggle (captain only)
                    cell.addEventListener("click", function() {
                        const captainList = container.getAttribute("data-captain").split(",").map(u => u.trim());
                        if (!captainList.includes(currentUser)) return;

                        const done = boardState[teamKey][`tile_${index}`];
                        boardState[teamKey][`tile_${index}`] = !done;
                        checkmark.style.display = !done ? "block" : "none";
                        cell.style.background = !done ? "rgba(76,175,80,0.5)" : "#313e59";

                        // Save to MediaWiki
                        $.post(mw.util.wikiScript('api'), {
                            action: 'edit',
                            title: 'Module:TeamBingo/data.json',
                            token: mw.user.tokens.get('csrfToken'),
                            format: 'json',
                            text: JSON.stringify(boardState, null, 4)
                        }).done(() => console.log("Board updated for everyone!"));
                    });

                    cell.appendChild(cellContainer);
                }
            }

            // Progress
            const progressDiv = document.createElement("div");
            progressDiv.style.marginTop = "10px";
            progressDiv.style.color = "#fff";
            progressDiv.className = "bingoProgress";
            container.appendChild(progressDiv);

            function updateProgress() {
                let completed = 0;
                for (let i = 0; i < parsedItems.length; i++)
                    if (boardState[teamKey][`tile_${i}`]) completed++;
                progressDiv.textContent = `Completed ${completed} of ${parsedItems.length} items`;
            }
            updateProgress();
        });
    }

    // Initial render
    fetchBoardData(function(boardData){
        containers.forEach(container => {
            const teamKey = container.getAttribute("data-team");
            renderBoard(container, teamKey);
        });
    });

    // --- Smart Polling every 5s ---
    setInterval(function() {
        fetchBoardData(function(newState){
            containers.forEach(container => {
                const teamKey = container.getAttribute("data-team");
                const cells = container.querySelectorAll("td");
                cells.forEach((cell,index)=>{
                    const checkmark = cell.querySelector(".bingoCheckmark");
                    const done = newState[teamKey][`tile_${index}`];
                    const oldDone = boardState[teamKey][`tile_${index}`];

                    if(done !== oldDone){
                        boardState[teamKey][`tile_${index}`] = done;
                        if(checkmark){
                            checkmark.style.display = done ? "block" : "none";
                            cell.style.background = done ? "rgba(76,175,80,0.5)" : "#313e59";
                        }
                    }
                });
            });
        });
    }, 5000);

});